Modifying the query on django rest framework

I’ve been messing about with filters on my listing (REST get) for my django backend. One problem I had is to show or list out only a certain entry based on a boolean value. I didn’t want to load all the spam and filter it, that would be useless… So I tinkered around and I was able to reset the queryset for the view by reassigning a new filter for a specific variable.

Here is the code:

class EnquiryView(viewsets.ModelViewSet):
    ...
    queryset = enquiry.objects.all().order_by('-created_at').exclude(is_spam=True)
  ...

    def list(self, request, *args, **kwargs):
       ...
        if (request.user.is_staff):
            if request.GET.get('attr',False):
                self.queryset = enquiry.objects.all().order_by('-created_at')
            return super(EnquiryView, self).list(request, *args, **kwargs)
        else:
            return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.