Adding a change in filtering settings

I have a ModelViewSet to which I want to add filtering. My simple model looks like

class Article(models.Model): date = = models.DateField() language = models.CharField(max_length=10) class Meta: ordering = ['-date'] 

And ModelViewSet (read-only):

 class ArticleViewSet(viewsets.ReadOnlyModelViewSet): queryset = Article.objects.all() serializer_class = ArticleSerializer 

API articles are now sorted by launch date, as you would expect. Now I allow filtering the language. I set the filter backend to DjangoFilterBackend in settings.py. My updated ModelViewSet now looks like this:

 class ArticleViewSet(viewsets.ReadOnlyModelViewSet): queryset = Article.objects.all() serializer_class = ArticleSerializer filter_fields = ['language'] 

This changes the order to ASC. Adding order_by('-date') to queryset does not change anything. Adding ordering = ('-date', ) does not change anything. => How to specify both filtering and order (or just use the default order when filtering is enabled)?

EDIT: The current functionality appears to come from the AutoFilterSet created in the Rest Framework by default: https://github.com/tomchristie/django-rest-framework/blob/822eb39599b248c68573c3095639a831ab6df99a/rest_framework/filterspy#L ... where order_by=True and passing this to django-filter get_ordering_field here: https://github.com/alex/django-filter/blob/d88b98dd2b70551deb9c128b209fcf783b325acc/django_filters/filterset.py#L325

=> It seems I need to create a FilterSet class:

 class LanguageFilter(django_filters.FilterSet): class Meta: model = Article fields = ['language'] order_by = model()._meta.ordering class ArticleViewSet(viewsets.ReadOnlyModelViewSet): queryset = Article.objects.all() serializer_class = ArticleSerializer filter_class = LanguageFilter 

Does this look right? It seems a bit "much" / verbose to keep the default order.

+7
django-rest-framework
source share
3 answers

Instead of implementing your own FilterSet , you can simply add OrderingFilter by specifying ordering = ['-date'] or better: ordering = Article._meta.ordering to restore the lost (default) order. It will also allow your users to use the ordering request parameter to override your default order.

+3
source share

Please note that this problem was resolved in master ... https://github.com/tomchristie/django-rest-framework/pull/1836 and should be released in version 2.4.3.

+1
source share

Good question.

It’s good to use an ordering filter in conjunction with Django-Filter, but I think it’s wrong that the Backback filter uses the reordering function.

In my case, I have to cache my random request, so I can no longer use Django-Filter, even if I do not filter on the first asynchronous page call.

0
source share

All Articles