Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Ordering with django-filter backend #1171

Hoohaha started this conversation in Ideas
Aug 21, 2023 · 1 comments · 2 replies
Discussion options

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']
You must be logged in to vote

Replies: 1 comment 2 replies

Comment options

The DjangoFilterBackend needs to be adjusted for this to be supported. What do you see is the advantage over the Django REST framework OrderingFilter?

You must be logged in to vote
2 replies
Comment options

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'),
 ),
Comment options

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Ideas
Labels
None yet
2 participants

AltStyle によって変換されたページ (->オリジナル) /