How to apply a filter backend to all fields of all resources in Django Rest Framework?
Right now you are telling Django REST Framework to use the DjangoFilterBackend
for all views, but you are not telling it how the FilterSet
should be generated.
django-filter
will automatically generate a FilterSet
for all of the fields on a model if the fields
are set to None
. Django REST Framework will automatically generate a FilterSet
if filter_fields
are not set to None
, which means you won't be able to use the default DjangoFilterBackend
.
You can create a custom DjangoFilterBackend
though, which will automatically generate the FilterSet
for all fields on the model.
from rest_framework.filters import DjangoFilterBackend
class AllDjangoFilterBackend(DjangoFilterBackend):
"""
A filter backend that uses django-filter.
"""
def get_filter_class(self, view, queryset=None):
"""
Return the django-filters `FilterSet` used to filter the queryset.
"""
filter_class = getattr(view, 'filter_class', None)
filter_fields = getattr(view, 'filter_fields', None)
if filter_class or filter_fields:
return super(AllDjangoFilterBackend, self).get_filter_class(self, view, queryset)
class AutoFilterSet(self.default_filter_set):
class Meta:
model = queryset.model
fields = None
return AutoFilterSet
This will still use the original filter backend for situations where the view defines a custom filter_class
or filter_fields
, but it will generate a custom FilterSet
for all other situations. Keep in mind that you shouldn't allow fields which aren't returned through the API to be filtered, as you are opening yourself up to future security issues (like people filtering a user list by passwords).