04.PageNumberPagination分页

一.使用默认分页

1.settings 设置
REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 2
}
2.参数
  • 1.第几页
    # Client can control the page using this query parameter.
    page_query_param = 'page'
    page_query_description = _('A page number within the paginated result set.')
  • 2.每页大小
    # Client can control the page size using this query parameter.
    # Default is 'None'. Set to eg 'page_size' to enable usage.
    page_size_query_param = None
    page_size_query_description = _('Number of results to return per page.')
  • 3.最大页
    # Set to an integer to limit the maximum page size the client may request.
    # Only relevant if 'page_size_query_param' has also been set.
    max_page_size = None

二.自定义分页

avue 前端分页参数:

# 前端很喜欢用 data,把 result 改成 data
{ "total": 40, "pagerCount": 5, "currentPage": 1, "pageSize": 20, "pageSizes": [ 10, 20, 30, 40, 50, 100 ], "background": true }
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from collections import OrderedDict, namedtuple

class LargeResultsSetPagination(PageNumberPagination):
    page_query_param = 'pagerCount'
    page_query_description = '当前第几页'
    page_size = 20
    page_size_query_param = 'pageSize'
    page_size_query_description = '每页条目数'
    max_page_size = 100

    def get_paginated_response(self, data):
        return Response(OrderedDict([
            ('total', self.page.paginator.count),
            ('next', self.get_next_link()),
            ('previous', self.get_previous_link()),
            ('data', data)
        ]))

# settings
REST_FRAMEWORK = {
    # 指定用于支持coreapi的Schema
    'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
    'DEFAULT_PAGINATION_CLASS': 'utils.utils.LargeResultsSetPagination',
    'PAGE_SIZE': 10,
}

结果如下
image

{
    "total": 104,
    "next": "http://127.0.0.1:8000/idcs/?pageSize=1&pagerCount=5",
    "previous": "http://127.0.0.1:8000/idcs/?pageSize=1&pagerCount=3",
    "data": [
        {
            "id": 4,
            "name": "华为机房0",
            "address": "神州路0号大院",
            "phone": "13412345678",
            "email": "mail_0@com.cn",
            "letter": "hw0"
        }
    ]
}

如果某个视图不需要分页,视图设置分页类为 None 即可

pagination_class = None
posted @ 2020-05-20 23:34  Jenvid  阅读(758)  评论(0编辑  收藏  举报