dorian

导航

 

  对于列表数据,REST framework提供了OrderingFilter过滤器来排序,可以快速指定排序字段。

  找到Applications/Examples/views/School.py文件最后一个类。

  在filter_backends中增加排序过滤器。代码如下:

from rest_framework import filters
from rest_framework.filters import OrderingFilter
class SchoolViewSet(GenericViewSet, mixins.ListModelMixin, mixins.CreateModelMixin, mixins.UpdateModelMixin,
                    mixins.RetrieveModelMixin, mixins.DestroyModelMixin):
    queryset = Schools.objects.all()
    serializer_class = SchoolsSerializer
    filter_backends = [OrderingFilter,filters.SearchFilter]
    search_fields = ('name',)
    ordering_fields = ('teacher_quantity', 'student_quantity', 'employment_rate')

  运行接口文档,找到SchoolViewSet 中的list方法,进行测试,效果如下:

 

   特别注意的是:排序字段必须经过序列化器,而序列化器中的临时字段是不能排序的。

 

posted on 2020-03-09 09:23  dorian  阅读(244)  评论(0编辑  收藏  举报