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?
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',
)
}
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',)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With