标签:lte img test rbac tsp mod return model tin
GenericAPIView为APIView的子类,它拓展了过滤、查询、分页的功能,本章主要介绍过滤的使用方法
from rest_framework.generics import 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)
pip install -i https://pypi.douban.com/simple django-filter
在项目下的settings.py模块中全局指定过滤引擎
INSTALLED_APPS = [ ‘django_filters‘ ]
from django_filters.rest_framework import DjangoFilterBackend
filter_backends = [DjangoFilterBackend]
在项目下的settings.py模块下的REST_FRAMEWORK中设置属性
REST_FRAMEWORK = { ‘DEFAULT_FILTER_BACKENDS‘: ‘django_filters.rest_framework.backends.DjangoFilterBackend‘ }
filterset_fields = [‘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 .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)
查询结果展示:
标签:lte img test rbac tsp mod return model tin
原文地址:https://www.cnblogs.com/xiaogongjin/p/13337956.html