2017-05-02 65 views
1

在django rest框架中,APIView使用与search filters相同的方法指定排序字段,因此我们可以使用相关名称指定排序。在django rest框架中重命名RelatedField排序过滤器

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

的路线是这样的:https://example.com/route?ordering=profile__profession

但是我们宁愿避免以显示API模型之间的关系,然后指定profession而不是profile__profession。如https://example.com/route?ordering=profession

这样做可以实现,而不必实施APIViewdef get_queryset(self):排序?

+0

我相信你可以使用django_filters在DRF过滤器后端做到这一点 - 如果这是一个选择:http://django-filter.readthedocs.io/en/develop/ref/filters。 HTML#orderingfilter – opalczynski

回答

1

它可以通过def get_queryset(self)的小改动来实现。

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

您需要根据Django REST框架编写属于自己的OrderingFilter,方法是覆盖get_ordering并使用字典将“短名称”映射到完整的查询集字符串。

相关问题