八、分页


返回

8.1 pageNumber分页

  • 基本的分页功能

  • utils/pagination.py:定义分页器类的属性值

    from rest_framework.pagination import PageNumberPagination
    
    
    class MyPagination(PageNumberPagination):
        """
        基本分页
        url?page=1&size=2
            每页2条,第1页
        """
        page_size = 1
        page_query_param = "page"
        page_size_query_param = "size"
        max_page_size = 3
               
    

8.2 limitOffset分页

  • 从某个位置开始,取多少条数据

  • utils/pagination.py:定义分页器类的属性值

    from rest_framework.pagination import LimitOffsetPagination
    
    
    class MyPagination(LimitOffsetPagination):
        """
        从特定位置开始查询数据
        url?limit=2&offset=3
            从第2条数据开始,往后找3条数据
        """
        default_limit = 1  # 设置默认向后找1条
        limit_query_param = "limit"
        offset_query_param = "offset"
        max_limit = 5  # 最大数据限制
    
    

8.3 Cursor分页

  • 游标分页,对游标加密

  • utils/pagination.py:定义分页器类的属性值

    from rest_framework.pagination import CursorPagination
    
    
    class MyPagination(CursorPagination):
        """
        游标分页
        url?cursor=加密游标
        """
        cursor_query_param = "cursor"
        page_size = 2
        ordering = "-id"  # 排序规则
    
    

8.4 视图

  • views.py

    from rest_framework.views import APIView
    from utils.pagination import MyPagination
    
    
    class BookView(APIView):
    
        def get(self, request):
            queryset = Book.objects.all()
            # 1 实例化分页器对象
            page_obj = MyPagination()
            # 2 对queryset分页
            page_queryset = page_obj.paginate_queryset(queryset, request, view=self)
            # 3 把分页好的数据序列化返回
            ser_obj = BookSerializer(page_queryset, many=True)
            return page_obj.get_paginated_response(ser_obj.data)
            
    

8.5 视图(利用框架)

  • views.py

    from utils.pagination import MyPagination
    from rest_framework.generics import GenericAPIView
    from rest_framework.mixins import ListModelMixin
    
    
    class BookView(GenericAPIView, ListModelMixin):
        queryset = Book.objects.all()
        serializer_class = BookSerializer
        pagination_class = MyPagination  # 配置分页器对象
    
        def get(self, request):
            # list方法中实现了分页逻辑
            return self.list(request)
    
    
返回