thisisms
thisisms

Reputation: 411

Django restframework generics.ListCreateAPIView returns list like objects

class UserProfileView(generics.ListCreateAPIView):
    permission_classes = (
    permissions.IsAuthenticated,
    )
    serializer_class = UserProfileSerializer

    def list(self,request):
        queryset = UserProfile.objects.filter(user=request.user.id)
        serializer = UserProfileSerializer(queryset, many=True)
        return Response(serializer.data)

I've got out pull like this

[
  {
    "id": 1,
    "firstname": "exp",
    "lastname": "exp"
  }
]

I wanted like this,How can i do that and i don't know why it's returning list like object, How can i fix this

{
    "id": 1,
    "firstname": "exp",
    "lastname": "exp",
}

Upvotes: 3

Views: 7503

Answers (1)

Sardorbek Imomaliev
Sardorbek Imomaliev

Reputation: 15390

ListCreateAPIView is designed to return list of objects.

Representation like this

{
    "id": 1,
    "firstname": "exp",
    "lastname": "exp",
}

Means you want an object, not list of objects, which means you need to get desired object by using RetrieveAPIView

There are no RetrieveCreateAPIView, but you can easily make with RetrieveModelMixin

Like this

from rest_framework import mixins, generics

class UserProfileView(mixins.RetrieveModelMixin, generics.CreateAPIView):
    permission_classes = (
        permissions.IsAuthenticated,
    )
    serializer_class = UserProfileSerializer

    # Custom get_object method which is gets from request
    # instead of queryset
    def get_object(self, queryset=None):
        return UserProfile.objects.get(user=self.request.user)

    # You can look this up in RetrieveAPIView
    def get(self, request, *args, **kwargs):
        return self.retrieve(request, *args, **kwargs)

Update

You need to overload get_object method, by default get_object will look in passed url parameters and try to get object from provided queryest. It is made like this to be generic for CRUDL usage. After that returned value from get_object is used to instantiate serializer_class. But in your case you need to just return current user in request. See updated answer. All this info can be understood if you look up retrieve method relaisation. For developer it is essential skill to know how to read source code.

Upvotes: 3

Related Questions