Django_rest-framework分页

文章目录

    • 配置settings,全局配置分页
    • 自定义Pagination类
    • 可选分页器
      • 1> PageNumberPagination
      • 2> LimitOffsetPagination

配置settings,全局配置分页

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS':  'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10  # 每页数目
}

自定义Pagination类

from collections import OrderedDict

from django.core.paginator import InvalidPage
from rest_framework.exceptions import NotFound
from rest_framework.pagination import PageNumberPagination

#http://127.0.0.1:9008/book/?page=1&page_size=6
from rest_framework.response import Response


class BookListPager(PageNumberPagination):
    page_size = 5  # 每页5条记录
    page_size_query_param = 'page_size'  # 每页记录数的参数名字


    # 自定义分页形式
    def get_paginated_response(self, data):
        return Response(OrderedDict([
            ('count', self.page.paginator.count),
            ('page_range', list(self.page.paginator.page_range)),  # 页码范围
            ('has_next', self.page.has_next()),
            ('has_prious', self.page.has_previous()),
            ('next_page_number', self.page.next_page_number()),
            ('results', data)
        ]))

注意:如果在视图内关闭分页功能,只需在视图内设置

pagination_class = None

可选分页器

1> PageNumberPagination

前端访问网址形式:

GET  http://api.example.org/books/?page=4

可以在⼦类中定义的属性:
page_size 每⻚数⽬
page_query_param 前端发送的⻚数关键字名,默认为"page"
page_size_query_param 前端发送的每⻚数⽬关键字名,默认为None
max_page_size 前端最多能设置的每⻚数量

from rest_framework.pagination import PageNumberPagination
    class StandardPageNumberPagination(PageNumberPagination):    page_size_query_param = 'page_size'

    max_page_size = 10

    class BookListView(ListAPIView):    queryset = BookInfo.objects.all().order_by('id')

    serializer_class = BookInfoSerializer
    pagination_class = StandardPageNumberPagination
    # 127.0.0.1/books/?page=1&page_size=2

2> LimitOffsetPagination

前端访问网址形式:

GET http://api.example.org/books/?limit=100&offset=400

可以在⼦类中定义的属性:
default_limit 默认限制,默认值与PAGE_SIZE设置⼀直
limit_query_paramlimit参数名,默认’limit’
offset_query_param offset参数名,默认’offset’
max_limit 最⼤limit限制,默认None

from rest_framework.pagination import LimitOffsetPagination
    class BookListView(ListAPIView):    queryset = BookInfo.objects.all().order_by('id')

    serializer_class = BookInfoSerializer
    pagination_class = LimitOffsetPagination
    # 127.0.0.1:8000/books/?offset=3&limit=2

你可能感兴趣的:(Django,python)