一、分页类型一
1、写一个分页类,继承 PageNumberPagination
web 用这个多
http://api.example.org/accounts/?page=4
http://api.example.org/accounts/?page=4&page_size=100
from rest_framework.pagination import PageNumberPagination, LimitOffsetPagination, CursorPagination
class CommonPageNumberPagination(PageNumberPagination):
# 重写几个类属性
page_size = 3 # 每页显示多少条
page_query_param = 'page' # 指定第几页的key值 http://127.0.0.1:8000/books/?page=3
page_size_query_param = 'size' # 可以指定每页显示多少条 size=300000
max_page_size = 5 # 每页最多显示5条
2、views
引入自定义的分页类
from .page import CommonPageNumberPagination
class BookView(ViewSetMixin, ListAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
pagination_class = CommonPageNumberPagination
3、效果

二、分页类型二
1、LimitOffsetPagination 使用场景
http://api.example.org/accounts/?limit=4 # 从开始取4条
http://api.example.org/accounts/?offset=4&limit=5 从第4条开始,取5条
from rest_framework.pagination import PageNumberPagination, LimitOffsetPagination, CursorPagination
class CommonLimitOffsetPagination(LimitOffsetPagination):
# http://api.example.org/accounts/?limit=4 # 从开始取4条
# http://api.example.org/accounts/?offset=4&limit=5 从第4条开始,取5条
default_limit = 2 # 默认每页显示2条
limit_query_param = 'limit' # 每页显示多少条的查询条件
offset_query_param = 'offset' # 从第几条开始取数据
max_limit = 5 # limit最多取5条
2、views 引入
from .page import CommonPageNumberPagination,CommonLimitOffsetPagination,CommonCursorPagination
class BookView(ViewSetMixin, ListAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
pagination_class = CommonLimitOffsetPagination
3、效果

三、分页类型三
1、CommonCursorPagination
app上用这个多
只能上一页和下一页,不能指定跳转到中间的某页---》效率高,大数据量用它、
from rest_framework.pagination import PageNumberPagination, LimitOffsetPagination, CursorPagination
class CommonCursorPagination(CursorPagination):
# app上用这个多
# 只能上一页和下一页,不能指定跳转到中间的某页---》效率高,大数据量用它、
cursor_query_param = 'cursor' # 查询条件,用不到,需要有
page_size = 2 # 每页显示两条
ordering = 'id' # 按id排序 这个必须是表中字段
2、引入略过
3、效果
