[Django]-Django โ€“ How can I filter in serializer

3๐Ÿ‘

If I understood your question correctly you wish to get list of instances in your view (using Django Rest Framework). The problem is that your view is inheriting from a generics.RetrieveAPIView. This view class calls self.retrieve(request, *args, **kwargs) method which returns you an object, not queryset. I think that you should inherit your view from a ListAPIView class. This class inherits ListModelMixin which

Provides a .list(request, *args, **kwargs) method, that implements listing a queryset.

So your code will be looking like this:

class User(generics.ListAPIView):
    serializer_class = RetrieveLocalSerializer
    queryset = User.objects.filter(
        fields_1=True,
        fields_2=False 
    )

See http://www.django-rest-framework.org/api-guide/generic-views/#listapiview for more information.

You may either define your queryset in a view or override get_queryset method:

queryset โ€“ The queryset that should be used for returning objects from this view. Typically, you must either set this attribute, or override the get_queryset() method. If you are overriding a view method, it is important that you call get_queryset() instead of accessing this property directly, as queryset will get evaluated once, and those results will be cached for all subsequent requests.

You may find more information here: http://www.django-rest-framework.org/api-guide/generic-views/#genericapiview

Hope this will help)

๐Ÿ‘คA. Grinenko

Leave a comment