一、使用方法
1.引入方式
from rest_framework.filters import OrderingFilter
2.添加引擎
将OrderingFilter引擎添加到filter_backends列表中,也可以添加到全局
filter_backends = [DjangoFilterBackend, OrderingFilter]
3.指定排序字段
使用ordering_fields指定需要排序的字段
ordering_fields = ['id', 'name', 'leader', 'programmer', 'tester']
二、完整代码展示
from rest_framework.response import Response from rest_framework import status from rest_framework.generics import GenericAPIView from django_filters.rest_framework import DjangoFilterBackend from rest_framework.filters import OrderingFilter from .models import Projects from .serializers import ProjectsModelSerializer class ProjectsPage(GenericAPIView): ''' 类视图 ''' queryset = Projects.objects.all() serializer_class = ProjectsModelSerializer filter_backends = [OrderingFilter] ordering_fields = ['id', 'name', 'leader', 'programmer', 'tester'] def get(self, request, pk=None): qs = self.get_queryset() qs = self.filter_queryset(qs) serializer_obj = self.get_serializer(instance=qs, many=True) return Response({'code': 0, 'res': "success", 'msg': serializer_obj.data}, status=status.HTTP_200_OK)
三、结果验证
如果是数字则默认为从小到大排序,字符串默认为以ASCII码从小到大排序,排序的查询字符串参数默认为ordering,如果要进行倒序排列,则在需要排序的字段前面指定一个减号(-)即可,如:ordering=-name