分页过滤器

分页过滤器

一、自定义分页器PageNumberPagination(常用)

# 1.自定义分页器.py
from rest_framework.pagination import PageNumberPagination
class CoursePageNumberPagination(PageNumberPagination):
    # 一页显示条数
    page_size = 2

    # 选择那一页的key,eg:?page=1
    page_query_param = "page"

    # 用户自定义一页显示的条数
    page_size_query_param = "page_size"

    # 用户自定义一页最大控制条数
    max_page_size = 10
# 2.使用
# 分页过滤器
from .paginations import CoursePageNumberPagination, CourseLimitOffsetPagination, CursorPagination

class FreeCourseListAPIView(ListAPIView):
    queryset = models.Course.objects.filter(is_delete=False, is_show=True).order_by('orders').all()
    serializer_class = serializers.FreeCourseModelSerializer
    

    # 自定义的分页器 http://127.0.0.1:8000/course/free?page=1&page_size=2
    pagination_class = CoursePageNumberPagination

​ 总结:

  1. 继承PageNumberPagination,重写属性字段,配置 pagination_class = CoursePageNumberPagination 使用url:http://127.0.0.1:8000/course/free?page=1&page_size=2,page:第一页,page_size:一页显示的数据条数

二、自定义分页器LimitOffsetPagination

# 1.自定义分页器.py
from rest_framework.pagination import LimitOffsetPagination
class CourseLimitOffsetPagination(LimitOffsetPagination):
    # 默认一页条数
    default_limit = 2
    # 从offset开始往后显示limit条
    limit_query_param = 'limit'
    offset_query_param = 'offset'
    max_limit = 2
# 2.使用
# 分页过滤器
from .paginations import CoursePageNumberPagination, CourseLimitOffsetPagination, CursorPagination

class FreeCourseListAPIView(ListAPIView):
    queryset = models.Course.objects.filter(is_delete=False, is_show=True).order_by('orders').all()
    serializer_class = serializers.FreeCourseModelSerializer
    

    # 自定义的分页器 (获取多少条数据的范围)
    """
    http://api.example.org/accounts/?limit=100
    http://api.example.org/accounts/?offset=400&limit=100(从400位置开始,获取100条数据)
    
    """
    
    pagination_class = CoursePageNumberPagination

三、自定义分页器CursorPagination

# 1.自定义分页器.py
from rest_framework.pagination import CursorPagination
class CourseCursorPagination(CursorPagination):
    cursor_query_param = 'cursor'
    page_size = 2
    page_size_query_param = 'page_size'
    max_page_size = 2
    # ordering = 'id'  # 默认排序规则,不能和排序过滤器OrderingFilter共存

# 2.使用
# 分页过滤器
from .paginations import CoursePageNumberPagination, CourseLimitOffsetPagination, CursorPagination

class FreeCourseListAPIView(ListAPIView):
    queryset = models.Course.objects.filter(is_delete=False, is_show=True).order_by('orders').all()
    serializer_class = serializers.FreeCourseModelSerializer    
    ordering_fields = ['price', 'id', 'students']


    # 自定义的分页器(必须与排序一起查询)必须添加排序规则(条件筛选过滤分页),会对连接加密
    # "next": "http://127.0.0.1:8000/course/free?cursor=cD0wLjAw&ordering=price&page_size=1",加密
    # http://127.0.0.1:8000/course/free?ordering=price&page_size=1
    pagination_class = CoursePageNumberPagination 
原文地址:https://www.cnblogs.com/randysun/p/12293120.html