Django REST Framework分页

时间:Nov. 14, 2019 分类:

目录:

分页

DRF提供了三种分页方式

  • PageNumberPagination
  • LimitOffsetPagination

PageNumberPagination

看第n页,每页显示n条数据

通过url传递参数的方式http://127.0.0.1:8000/book?page=2&size=1

class MyPageNumber(PageNumberPagination):
    page_size = 2  # 每页显示多少条
    page_size_query_param = 'size'  # URL中每页显示条数的参数
    page_query_param = 'page'  # URL中页码的参数
    max_page_size = None  # 最大页码数限制

视图逻辑

class BookView(APIView):
    def get(self, request):
        book_list = Book.objects.all()
        # 分页
        page_obj = MyPageNumber()
        page_article = page_obj.paginate_queryset(queryset=book_list, request=request, view=self)

        ret = BookSerializer(page_article, many=True)
        return Response(ret.data)
        # 返回带超链接 需返回的时候用内置的响应方法
        # return page_obj.get_paginated_response(ret.data)

LimitOffsetPagination

在第n个位置,向后查看n条数据

通过url传递参数的方式http://127.0.0.1:8000/book?offset=2&limit=1

class MyLimitOffset(LimitOffsetPagination):
    default_limit = 1
    limit_query_param = 'limit'
    offset_query_param = 'offset'
    max_limit = 999

视图逻辑

# 视图和上面的大体一致
# 只有用的分页类不同,其他都相同
class BookView(APIView):
    def get(self, request):
        book_list = Book.objects.all()
        # 分页
        page_obj = MyLimitOffset()
        page_article = page_obj.paginate_queryset(queryset=book_list, request=request, view=self)

        ret = BookSerializer(page_article, many=True)
        # return Response(ret.data)
        # 返回带超链接 需返回的时候用内置的响应方法
        return page_obj.get_paginated_response(ret.data)

CursorPagination

加密游标的分页,把上一页和下一页的id记住

class MyCursorPagination(CursorPagination):
    cursor_query_param = 'cursor'
    page_size = 1
    ordering = '-id'

视图逻辑

class BookView(APIView):
    def get(self, request):
        book_list = Book.objects.all()
        # 分页
        page_obj = MyCursorPagination()
        page_article = page_obj.paginate_queryset(queryset=book_list, request=request, view=self)

        ret = BookSerializer(page_article, many=True)
        # return Response(ret.data)
        # 返回带超链接 需返回的时候用内置的响应方法
        return page_obj.get_paginated_response(ret.data)