rest_framework 之分页器
一 分页器--准备
1.1 基本参数
# 普通分页 from rest_framework.pagination import PageNumberPagination # 偏移分页 from rest_framework.pagination import LimitOffsetPagination # 加密分页 from rest_framework.pagination import CursorPagination class MyPageNumberPagination(PageNumberPagination): # 每页显示多少条 page_size = 3 # 查询的key,问号后面的key page_query_param = 'aa' # 指定当前页显示多少条 page_size_query_param='size' # 每页最多显示多少条 max_page_size=4
1.2 普通分页
class Book(ViewSetMixin, APIView): def get_all(self, request): response = {'status': 100, 'msg': '查询成功'} book_list = models.Book.objects.all() # 实例化产生一个分页对象 # 不继承来修改对象的值 page=PageNumberPagination() page.page_size=2 page.page_query_param='bb' # page = MyPageNumberPagination() # 第一个参数:要分页的数据,第二个参数request对象,第三个参数,当前视图对象 page_list = page.paginate_queryset(book_list, request, self) # 再序列化的时候,用分页之后的数据 ser = mySer.BookSerializer(instance=page_list, many=True) # response['data'] = ser.data # return Response(response) # 会带着链接,和总共的条数(不建议用) return page.get_paginated_response(ser.data) # return Response(ser.data)
1.3 偏移分页
# 偏移分页 from rest_framework.pagination import LimitOffsetPagination class Book(ViewSetMixin, APIView): def get_all(self, request): response = {'status': 100, 'msg': '查询成功'} book_list = models.Book.objects.all() # 实例化产生一个偏移分页对象 page=LimitOffsetPagination() page.default_limit=3 page.max_limit=5 page_list = page.paginate_queryset(book_list, request, self) ser = mySer.BookSerializer(instance=page_list, many=True) return Response(ser.data)
1.4 加密分页
from rest_framework.pagination import CursorPagination class Book(ViewSetMixin, APIView): def get_all(self, request): response = {'status': 100, 'msg': '查询成功'} book_list = models.Book.objects.all() # 实例化产生一个加密分页对象 page = CursorPagination() page.ordering = 'nid' page_list = page.paginate_queryset(book_list, request, self) ser = mySer.BookSerializer(instance=page_list, many=True) return page.get_paginated_response(ser.data)
二 settings
REST_FRAMEWORK = { # 每页显示两条 'PAGE_SIZE':2 }
三 路由
url(r'^books/$', views.Book.as_view()),