Append an entry per view to the DEFAULT_FILTER_BACKENDS
In a Django (and DRF) project with a large number of views we have set a list of filter backends in settings.py
:
REST_FRAMEWORK = {
"DEFAULT_FILTER_BACKENDS": [
# filter backend classes
],
# other settings
}
Some of the view classes need additional filter backends. We can specify the attribute filter_backends
per view class:
FooViewSet(viewsets.ModelViewSet):
filter_backends = [DefaultFilterOne, DefaultFilterTwo, DefaultFilterThree, AdditionalFilter]
However, this is not DRY. Here in this example three (3) filter backends are default and have to be repeated in the viewset class. If there's a change in settings.py
it has to be reflected in the view class.
What is best practice to append an additional filter backend per class, while keeping the default filter backends from settings.py
?
Thanks to the hint from @LiorA I solved this issue. This is how I did it:
from rest_framework.settings import api_settings
from rest_framework import viewsets
class FooViewSet(viewsets.ModelViewSet):
filter_backends = api_settings.DEFAULT_FILTER_BACKENDS + [AdditionalFilter]
Here api_settings.DEFAULT_FILTER_BACKENDS
fetches the entry "DEFAULT_FILTER_BACKENDS" from REST_FRAMEWORK
in settings.py
. While the entries in the settings are paths as strings, api_settings
converts the values to class references.