-
Notifications
You must be signed in to change notification settings - Fork 300
-
django-filter support ordering as well.
User can reuse ordering from django-filter, rather than rest_framework.filters.OrderingFilter
https://django-filter.readthedocs.io/en/stable/ref/filters.html#orderingfilter
Sample code: declare sort param in FilterSet:
class UserFilter(FilterSet): account = CharFilter(field_name='username') status = NumberFilter(field_name='status') order_by_field = 'sort' sort = OrderingFilter( # tuple-mapping retains order fields=( ('username', 'account'), ('first_name', 'first_name'), ('last_name', 'last_name'), ), # labels do not need to retain order field_labels={ 'username': 'User account', } ) class Meta: model = User fields = ['first_name', 'last_name']
Beta Was this translation helpful? Give feedback.
All reactions
Replies: 1 comment 2 replies
-
The DjangoFilterBackend needs to be adjusted for this to be supported. What do you see is the advantage over the Django REST framework OrderingFilter?
Beta Was this translation helpful? Give feedback.
All reactions
-
With django-filter backend, you can easily use alias name to sort.
For example, sort a field from foreign relationship. you can use alias name instead of model__foreign__filed.
fields=( ('username', 'account__username'), ('first_name', 'account__firstname'), ('last_name', 'account__lastname'), ),
Beta Was this translation helpful? Give feedback.
All reactions
-
Fair enough. I think to support this, only the DjangoFilterBackend needs to be adjusted. Not sure whether something like this should be directly included in DJA or whether it should simply be documented for the users who need it.
The custom django filter backend class which supports ordering could look like the following. This is not tested though and off the top of my head, but should be a starting point.
from rest_framework_json_api.django_filters.backends import DjangoFilterBackend class DjangoFilterBackendWithOrdering(DjangoFilterBackend): def get_filterset_kwargs(self, request, queryset, view): filterset_kwargs = super().get_filterset_kwargs(self, request, queryset, view) if 'sort' in request.query_params: filterset_kwargs['filter_keys'].append('sort') return filterset_kwargs
If you have a use case and could test this, adjust as needed and share it, that would be very helpful.
Beta Was this translation helpful? Give feedback.