DRF框架GenericAPIView之分页查询
一、使用方法
1.添加引擎
在全局配置settings.py模块的REST_FRAMEWORK字段中配置引擎和指定每页显示的数据条数
REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 5 }
2.引入方式
使用self.paginate_queryset()方法进行分页,它需要传一个查询集对象参数,如果没有进行分页,则会返回None,因此需要做一个if判断,并使用self.get_paginated_response()序列化输出分页后的数据,该方法接收一个序列化器对象.data参数
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.filter_queryset(self.get_queryset()) page = self.paginate_queryset(qs) if page: serializer_obj = self.get_serializer(instance=page, many=True) return self.get_paginated_response({'code': 0, 'res': "success", 'msg': serializer_obj.data}) serializer_obj = self.get_serializer(instance=qs, many=True) return Response({'code': 0, 'res': "success", 'msg': serializer_obj.data}, status=status.HTTP_200_OK)
验证结果:
3.指定页展示指定的数据条数
在PageNumberPagination类中,我们可以对一些字段值进行重写,先看看源码
1.重写PageNumberPagination
我们直接新建一个pagination.py模块,在该模块中创建一个类PageNumberPagination父类,并重写类属性,并且自定义的属性优先级最高,如果全局配置中也有相关配置,则直接会被覆盖
from rest_framework.pagination import PageNumberPagination class NewPagination(PageNumberPagination): page_size = 5 max_page_size = 50 page_size_query_param = 'size'
2.配置引擎
将新建的NewPagination的引用地址,配置到全局配置settings.py模块的REST_FRAMEWORK字段中,并将原先的注释掉
REST_FRAMEWORK = { # 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', # 'PAGE_SIZE': 5, 'DEFAULT_PAGINATION_CLASS': 'utils.pagination.NewPagination' }
验证结果:
4.在视图中指定分页引擎类
在上面我们的分页引擎都是配置到全局中的,如果不希望所有的查询接口都支持该功能,我们可以只指定当前接口所属的视图,这时就不需要在全局配置中配置分页引擎,直接在视图中使用pagination_class类属性指定分页引擎
from django.db import connection from django.http import Http404from rest_framework.response import Response from rest_framework import status from rest_framework.generics import GenericAPIView from utils.pagination import NewPagination from .models import Projects from .serializers import ProjectsModelSerializer class ProjectsPage(GenericAPIView): ''' 类视图 ''' queryset = Projects.objects.all() serializer_class = ProjectsModelSerializer pagination_class = NewPagination def get(self, request): qs = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(qs) if page: serializer_obj = self.get_serializer(instance=page, many=True) return self.get_paginated_response({'code': 0, 'res': "success", 'msg': serializer_obj.data}) serializer_obj = self.get_serializer(instance=qs, many=True) return Response({'code': 0, 'res': "success", 'msg': serializer_obj.data}, status=status.HTTP_200_OK)
作者:小公瑾
-------------------------------------------
个性签名:不忘初心,方得始终!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!