So now I don’t understand where the filtering is done or how to remove this duplicated code. Is there something I’ve missed on a more fundamental level?
The filtering happens inside the filter_queryset method. The drf code is very opinionated and object oriented. The ReadOnlyModelViewSet is made up of two mixins. When you’re making a list
request, it’s being handled by the ListModelMixin
’s list method.
To extend the filtering behavior that already exists on the viewset, you can extend the filter_queryset method
def filter_queryset(self, queryset):
queryset = super().filter_queryset(queryset)
extra_field1 = self.request.query_params.get('extra_field1')
if extra_field1:
queryset = queryset.filter(extra_field1=extra_field1)
return queryset
If you haven’t done so yet, take the time to go through the django rest framework tutorial