Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use limit in django rest framework generics.RetrieveAPIView

As generics.RetrieveAPIView in django rest framework should return only one record, i would like to use a limit in get query method like given below

class PortUserView(generics.RetrieveAPIView):
    lookup_field = 'user'

    def get_queryset(self):

        return PortUser.objects.all()[:1]

getting error like this "Cannot filter a query once a slice has been taken".

whats is wrong with my code?

like image 984
asitm9 Avatar asked Aug 07 '15 11:08

asitm9


People also ask

What is the difference between APIView and GenericAPIView?

GenericAPIView is a more loaded version of APIView . It isn't really useful on its own but can be used to create reusable actions. Mixins are bits of common behavior. They're useless without GenericAPIView .

What is RetrieveAPIView?

RetrieveAPIView. Used for read-only endpoints to represent a single model instance. Provides a get method handler. Extends: GenericAPIView, RetrieveModelMixin.

How do you pass extra context data to Serializers in Django REST Framework?

In function-based views, we can pass extra context to serializer with “context” parameter with a dictionary. To access the extra context data inside the serializer we can simply access it with “self. context”. From example, to get “exclude_email_list” we just used code 'exclude_email_list = self.


2 Answers

There is no need for you to worry about returning a single object from the queryset at the time of retrieve. DRF will handle that automatically for you using its .get_object() defined in the GenericAPIView.

You can just use the below code and DRF will handle the retrieve action for you.

class PortUserView(generics.RetrieveAPIView):
    lookup_field = 'user'
    queryset = PortUser.objects.all()

get_object(self)

Returns an object instance that should be used for detail views. Defaults to using the lookup_field parameter to filter the base queryset.

Source code for retrieve action:

def retrieve(self, request, *args, **kwargs):
    instance = self.get_object() # here the object is retrieved
    serializer = self.get_serializer(instance)
    return Response(serializer.data)

We can see that DRF uses the .get_object() function to get the object from the queryset. To perform the filtering, it uses the lookup_field defined in the view.

Here is the actual get_object() code to make things more clear.

def get_object(self):
        """
        Returns the object the view is displaying.

        You may want to override this if you need to provide non-standard
        queryset lookups.  Eg if objects are referenced using multiple
        keyword arguments in the url conf.
        """
        queryset = self.filter_queryset(self.get_queryset())

        # Perform the lookup filtering.
        lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field

        assert lookup_url_kwarg in self.kwargs, (
            'Expected view %s to be called with a URL keyword argument '
            'named "%s". Fix your URL conf, or set the `.lookup_field` '
            'attribute on the view correctly.' %
            (self.__class__.__name__, lookup_url_kwarg)
        )

        filter_kwargs = {self.lookup_field: self.kwargs[lookup_url_kwarg]}
        obj = get_object_or_404(queryset, **filter_kwargs) # <-- can see that filtering is performed on the base of 'lookup_field'

        # May raise a permission denied
        self.check_object_permissions(self.request, obj)

        return obj # will return the single retrieved object
like image 98
Rahul Gupta Avatar answered Sep 28 '22 10:09

Rahul Gupta


You don't need to do this. Instead you should let the framework filter your queryset:

class PortUserView(generics.RetrieveAPIView):
    queryset =  PortUser.objects.all()
like image 32
DrfProgrammer Avatar answered Sep 28 '22 08:09

DrfProgrammer