GenericAPIView为APIView的子类,它拓展了过滤、查询、分页的功能,本章主要介绍过滤的使用方法
from rest_framework.generics import GenericAPIView
from rest_framework.response import Responsefrom rest_framework import statusfrom rest_framework.generics import GenericAPIViewfrom .models import Projectsfrom .serializers import ProjectsModelSerializerclass 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 Responsefrom rest_framework import statusfrom rest_framework.generics import GenericAPIViewfrom django_filters.rest_framework import DjangoFilterBackendfrom .models import Projectsfrom .serializers import ProjectsModelSerializerclass 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)
查询结果展示: