Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use OrderingFilter along with other Filterset filtering on a model

I have a model lets say ObservedMoves. This model is referenced in many queries inside my views. So instead of applying the filters that I want directly inside each view I have them abstracted inside a filterclass let's say ObservedMovesFilters that subclasses django_filters.Filterset and has a meta field model = ObservedMoves.

Now what I want to do is to enable the user to specify the ordering field when giving a request. For that I plan to use DRF's OrderingFilter. If I try to subclass the OrderingFilter class instead of the Filterset class the filters don't work. If I specify OrderingFilter as the default filter backend again the filters don't work.

In DRF's documentation the only method presented is specifying inside a view the alternative filter back end and also specify the ordering parameters but I want to avoid explicitly defining it in every view that queries that model. Is there a way to do that?

like image 622
LetsPlayYahtzee Avatar asked Nov 11 '15 14:11

LetsPlayYahtzee


2 Answers

If I'm understanding you correctly you don't have to add filter_backends to every ViewSet like the other answer says.

You can just set up your default filter backends in your settings.py file like this:

REST_FRAMEWORK = {
    'DEFAULT_FILTER_BACKENDS': (
        'rest_framework.filters.DjangoFilterBackend',
        'rest_framework.filters.OrderingFilter',
    )
}
like image 91
emptyflash Avatar answered Oct 18 '22 21:10

emptyflash


You have to specify another field on the ViewSet called filter_backends

filter_backends = (filters.DjangoFilterBackend,filters.OrderingFilter,)

e.g.

from rest_framework import filters
import django_filters

class UserFilter(django_filters.FilterSet):
    [...]

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    #vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
    filter_backends = (filters.DjangoFilterBackend,filters.OrderingFilter,)
    filter_class = UserFilter
    ordering = ('username',)
like image 24
Ross Rogers Avatar answered Oct 18 '22 22:10

Ross Rogers