[Fixed]-Django REST Framework filter backend

1👍

✅

The problem here is that you’ve subclassed GenericAPIView and then not (re-)implemented any of the handy logic that Django REST Framework provides in its concrete view class.

Instead you want to subclass ListAPIView which provides a get method implementing the filtering behaviour you’re looking for.

The magic all resides in ListModelMixin which filters the queryset as needed…

class ListModelMixin(object):
    """
    List a queryset.
    """
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        ... method continues ...

Your final view class should then look something like this:

class OperatorList(generics.ListAPIView):

    permission_classes = (permissions.IsAuthenticated, IsAdmin)

    filter_class = OperatorsFilter
    serializer_class = OperatorSerializer

    def get_queryset(self):
        queryset = self.request.user.operators.all()

I hope that helps.

Leave a comment