Mike Doudkin
Mike Doudkin

Reputation: 638

Django REST Framework filter backend

I try to implement some basic filtering on my GenericAPIView, like this:

The issue is that filters are displayed in browsable API, but 'Created' is not a DateTimeWidget, but a simple input. Also, applying filter takes no effect, and I still have to catch request.query_params in get_queryset() (I ama trying to use filter backend to avoid this in first turn).

Does anybody have any suggestions?

Upvotes: 0

Views: 2030

Answers (1)

Carlton Gibson
Carlton Gibson

Reputation: 7386

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.

Upvotes: 1

Related Questions