分页模式
rest framework中提供了三种分页模式:
from rest_framework.pagination import PageNumberPagination, LimitOffsetPagination, CursorPagination
全局配置
settingt.py
REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 10 }
在视图中进行局部设置
class PublisherViewSet(ModelViewSet): queryset = models.Publisher.objects.all() serializer_class = PublisherModelSerializer pagination_class = PageNumberPagination # 注意不是列表(只能有一个分页模式)
按页码数分页,第n页,每页显示m条数据
例如:http://127.0.0.1:8089/admin/users/?pagenum=1&pagesize=10
分页器
class MyPageNumberPagination(PageNumberPagination): page_size = 10 # 表示每页的默认显示数量 max_page_size = 50 # max_page_size:表示每页最大显示数量,做限制使用,避免突然大量的查询数据,数据库崩溃 page_size_query_param = 'pagesize' # page_size_query_param:表示url中每页数量参数 page_query_param = 'pagenum' # page_query_param:表示url中的页码参数
视图(返回带页码链接的响应,有总条数)
class UserView(APIView): def get(self, request, *args, **kwargs): pk = kwargs.get('pk') # 获取单挑数据 id 值 ret = { "data": { "users": [] }, "meta": { "status": 200, "message": "" } } page = MyPageNumberPagination() if not pk: queryset = User.objects.all() page_user = page.paginate_queryset(queryset=queryset, request=request, view=self) ser = UserSerializer(instance=page_user, many=True) ret["data"]["users"] = ser.data return page.get_paginated_response(ret) # return Response(ret) # Response 只接受列表,字典,字符串类型的数据 else: if User.objects.filter(pk=pk): obj_dict = User.objects.filter(pk=pk).first() ser = UserSerializer(instance=obj_dict, many=False) ret["data"]["users"] = ser.data else: ret["meta"]["status"] = 500 ret["meta"]["message"] = "系统报错" return Response(ret)