DRF框架GenericAPIView之排序查询
2021-04-14 09:27
标签:res color tsp 添加 mic lse info 使用方法 ken 将OrderingFilter引擎添加到filter_backends列表中,也可以添加到全局 使用ordering_fields指定需要排序的字段 如果是数字则默认为从小到大排序,字符串默认为以ASCII码从小到大排序,排序的查询字符串参数默认为ordering,如果要进行倒序排列,则在需要排序的字段前面指定一个减号(-)即可,如:ordering=-name DRF框架GenericAPIView之排序查询 标签:res color tsp 添加 mic lse info 使用方法 ken 原文地址:https://www.cnblogs.com/xiaogongjin/p/13338019.html一、使用方法
1.引入方式
from rest_framework.filters import OrderingFilter
2.添加引擎
filter_backends = [DjangoFilterBackend, OrderingFilter]
3.指定排序字段
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)
三、结果验证
1.顺序排序
2.倒序排序
下一篇:python网站发布
文章标题:DRF框架GenericAPIView之排序查询
文章链接:http://soscw.com/index.php/essay/75604.html