简体   繁体   中英

Rename RelatedField ordering filter in django rest framework

In a django rest framework APIView we specify ordering fields using the same method as the search filters and therefore we can specify ordering using related names.

ordering_fields = ('username', 'email', 'profile__profession')

The route would look like this: https://example.com/route?ordering=profile__profession

However we would rather avoid to display the relation between the models in the api and then specify profession instead of profile__profession . Such as https://example.com/route?ordering=profession

Can this be achieved without having to implement the sorting in the APIView 's def get_queryset(self): ?

It can be achieved with a minor change in def get_queryset(self) .

def get_queryset(self):
    query = super(UserListView, self).get_queryset().annotate(profession=F('profile__profession'))
    return query

您需要通过覆盖get_ordering并使用字典将“短名称”映射到完整的查询集字符串,基于Django REST框架编写自己的OrderingFilter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM