分页器
三种分页方式:
- PageNumberPagination
- LimitOffsetPagination
- CursorPagination
#settings.py全局配置
REST_FRAMEWORK = {
'PAGE_SIZE': 2,
}
PageNumberPagination
# urls.py
path('books2/', views.BookListView.as_view()),#继承了ListAPIView
#views.py
from rest_framework.generics import ListAPIView
from rest_framework.pagination import PageNumberPagination, LimitOffsetPagination, CursorPagination
#重写
class MyPageNumberPagination(PageNumberPagination):
page_size = 3 # 每页显示的条数
# page_query_param = 'num' # 前端发送的页数关键字,默认为'page'
max_page_size = 5 # 每页最大显示条数
page_size_query_param = 'size'#每一页显示的条数
class BookListView(ListAPIView):
queryset = Book.objects.all()
serializer_class = BookModelSerializer
# 配置分页
pagination_class = MyPageNumberPagination
#http://127.0.0.1:8000/api/books2/?num=2
#http://127.0.0.1:8000/api/books2/?num=2&size=6 #一页最多显示5数据
LimitOffsetPagination
# urls.py
path('books2/', views.BookListView.as_view()),#继承了ListAPIView
#views.py
class MyLimitOffsetPagination(LimitOffsetPagination):
default_limit = 3 #每页条数
limit_query_param = 'limit' #往后拿几条
offset_query_param = 'offset' #从第几个开始
max_limit = 5
class BookListView(ListAPIView):
queryset = Book.objects.all()
serializer_class = BookModelSerializer
# 配置分页
pagination_class = MyLimitOffsetPagination
#http://127.0.0.1:8000/api/books2/?offset=6&limit=2
CursorPagination
写出来只有上一页,下一页,不能跳
# urls.py
path('books2/', views.BookListView.as_view()),#继承了ListAPIView
#views.py
class MyCursorPagination(CursorPagination):
page_size = 2 # 每一页显示的条数
cursor_query_param = 'cursor' # 每一页查询的key
ordering = '-id' # 排序
class BookListView(ListAPIView):
queryset = Book.objects.all()
serializer_class = BookModelSerializer
# 配置分页
pagination_class = MyCursorPagination
使用APIView写分页
#urls.py
path('books3/', views.BookView.as_view()),
#views.py
from rest_framework.pagination import PageNumberPagination, LimitOffsetPagination, CursorPagination
from rest_framework.views import APIView
from rest_framework.response import Response
from app01.models import Book
from app01.serialize import BookModelSerializer
#重写
class MyPageNumberPagination(PageNumberPagination):
page_size = 3 # 每页显示的条数
page_query_param = 'num' # 前端发送的页数关键字,默认为'page'
max_page_size = 5 # 每页最大显示条数
page_size_query_param = 'size' # 每一页显示的条数
class BookView(APIView):
def get(self, request, *args, **kwargs):
book_list = Book.objects.all()
# 实例化得到分页器对象
page_cursor = MyPageNumberPagination()
book_list = page_cursor.paginate_queryset(book_list, request, view=self)
next_url = page_cursor.get_next_link() # 下一页
pre_url = page_cursor.get_previous_link() # 上一页
print(next_url)#打印下一页的url
print(pre_url)#打印下一页的url
book_ser = BookModelSerializer(book_list, many=True)
return Response(data=book_ser.data)
本文来自博客园,作者:ExpiredSaury,转载请注明原文链接:https://www.cnblogs.com/saury/p/16976725.html