Movatterモバイル変換


[0]ホーム

URL:


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 inIdeas
Aug 21, 2023· 1 comments· 2 replies
Discussion options

django-filter support ordering as well.
User can reuse ordering from django-filter, rather thanrest_framework.filters.OrderingFilter

https://django-filter.readthedocs.io/en/stable/ref/filters.html#orderingfilter
Sample code: declaresort param inFilterSet:

classUserFilter(FilterSet):account=CharFilter(field_name='username')status=NumberFilter(field_name='status')order_by_field='sort'sort=OrderingFilter(# tuple-mapping retains orderfields=(            ('username','account'),            ('first_name','first_name'),            ('last_name','last_name'),        ),# labels do not need to retain orderfield_labels={'username':'User account',        }    )classMeta:model=Userfields= ['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
@Hoohaha
Comment options

Withdjango-filter backend, you can easily use alias name to sort.
For example, sort a field from foreign relationship. you can use alias name instead ofmodel__foreign__filed.

fields=(            ('username','account__username'),            ('first_name','account__firstname'),            ('last_name','account__lastname'),        ),
@sliverc
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.

fromrest_framework_json_api.django_filters.backendsimportDjangoFilterBackendclassDjangoFilterBackendWithOrdering(DjangoFilterBackend):defget_filterset_kwargs(self,request,queryset,view):filterset_kwargs=super().get_filterset_kwargs(self,request,queryset,view)if'sort'inrequest.query_params:filterset_kwargs['filter_keys'].append('sort')returnfilterset_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 freeto join this conversation on GitHub. Already have an account?Sign in to comment
Category
Ideas
Labels
None yet
2 participants
@Hoohaha@sliverc

[8]ページ先頭

©2009-2025 Movatter.jp