[Django]-Django restframework generics.ListCreateAPIView returns list like objects

3👍

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.

Leave a comment