[Django]-Override ModelViewSet's queryset with filter backends applied

7👍

Yes you can. Just extend filter_queryset method of ViewSet

class MyModelViewSet(viewsets.ModelViewSet):
    filter_backends = (CustomFilter, )
    serializer_class = MySerializer

    def filter_queryset(self, queryset):
        # super needs to be called to filter backends to be applied
        queryset = super().filter_queryset(queryset)
        # some extra filtering
        return queryset

In action methods in ViewSet it actually does this

queryset = self.filter_queryset(self.get_queryset())

So your queryset that is sent to serializer is the one that created by get_queryset and then filtered with filter_queryset

Leave a comment