DRF框架GenericAPIView之过滤查询
2020-12-28 00:28
标签:lte img test rbac tsp mod return model tin GenericAPIView为APIView的子类,它拓展了过滤、查询、分页的功能,本章主要介绍过滤的使用方法 在项目下的settings.py模块中全局指定过滤引擎 在项目下的settings.py模块下的REST_FRAMEWORK中设置属性 查询结果展示: DRF框架GenericAPIView之过滤查询 标签:lte img test rbac tsp mod return model tin 原文地址:https://www.cnblogs.com/xiaogongjin/p/13337956.html一、引入方式
from rest_framework.generics import GenericAPIView
二、GenericAPIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.generics import GenericAPIView
from .models import Projects
from .serializers import ProjectsModelSerializer
class ProjectsPage(GenericAPIView):
‘‘‘
类视图
‘‘‘
queryset = Projects.objects.all()
serializer_class = ProjectsModelSerializer
def get(self, request):
qs = self.get_queryset()
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.安装django-filter第三方库
pip install -i https://pypi.douban.com/simple django-filter
2.配置django-filter
INSTALLED_APPS = [
‘django_filters‘
]
3.引入方式
from django_filters.rest_framework import DjangoFilterBackend
4.使用方法
a.在视图中指定过滤引擎,也可以在全局指定
1)视图中指定,如果要指定多个引擎,直接继续添加到该列表中
filter_backends = [DjangoFilterBackend]
2)全局指定
REST_FRAMEWORK = {
‘DEFAULT_FILTER_BACKENDS‘: ‘django_filters.rest_framework.backends.DjangoFilterBackend‘
}
b.指定需要过滤的字段,过滤的字段需要与模型类中的字段保持一致
filterset_fields = [‘name‘, ‘leader‘, ‘programmer‘, ‘tester‘]
c.调用self.filter_queryset()方法,传递一个查询集对象,并返回一个查询集
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 .models import Projects
from .serializers import ProjectsModelSerializer
class ProjectsPage(GenericAPIView):
‘‘‘
类视图
‘‘‘
queryset = Projects.objects.all()
serializer_class = ProjectsModelSerializer
filter_backends = [DjangoFilterBackend]
filterset_fields = [‘name‘, ‘leader‘, ‘programmer‘, ‘tester‘]
def get(self, request):
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)
下一篇:C语言程序设计报告七
文章标题:DRF框架GenericAPIView之过滤查询
文章链接:http://soscw.com/index.php/essay/38710.html