1. 分页器分为:简单分页器与偏移分页器和加密分页器
2.实现一个简单的分页器的用法:
# 简单分页 # 第一步,导入分页类 # from rest_framework.pagination import PageNumberPagination # class MyPageNumberPagination(PageNumberPagination): # page_size=4 # # class BooksView(APIView): # def get(self, request): # response = CommonResponse() # book_list = models.Book.objects.all() # # # 第二步:实力化产生一个分页类对象,不需要传参数 # page_pagination = PageNumberPagination() # #*****重点,4个参数 # page_pagination.page_size=4 # page_pagination.page_query_param='xx' # page_pagination.page_size_query_param='max' # # page_pagination.max_page_size=7 # # # 第一个参数是要分页的queryset对象,第二个参数是request对象 # ret = page_pagination.paginate_queryset(book_list, request, self) # #第三步,再序列化的时候用ret对象 # book_ser = BookSerializer(instance=ret, many=True) # response.msg = '查询成功' # response.data = book_ser.data # # return Response(response.get_dic) # return page_pagination.get_paginated_response(book_ser.data)
3. 加密分页器的实现:
#CursorPagination 分页 # from rest_framework.pagination import CursorPagination # class BooksView(APIView): # def get(self, request): # response = CommonResponse() # book_list = models.Book.objects.all() # page_pagination = CursorPagination() # #重点的参数 # page_pagination.ordering='nid' # # page_pagination.page_size=3 # # # ret = page_pagination.paginate_queryset(book_list, request, self) # book_ser = BookSerializer(instance=ret, many=True) # response.msg = '查询成功' # response.data = book_ser.data # # return Response(response.get_dic) # return page_pagination.get_paginated_response(book_ser.data)
4. settings做相应的配置
# 所有drf的配置,都放在这个字典中 REST_FRAMEWORK={ #第四步,配置每页显示的条数 #每页显示3条 'PAGE_SIZE':3 }
5. 分页器案例分析:
分页器 1 简单分页(查看第n页,每页显示n条) -使用方法 -1 导入PageNumberPagination类 -2 实例化产生一个对象 -page_pagination = PageNumberPagination() -3 需要配置四个参数:page_size,page_query_param,page_size_query_param,max_page_size -page_size必须指定:在setting中指定或者直接赋值 -4 调用下面的方法,返回ret数据 ret = page_pagination.paginate_queryset(book_list, request, self) -5 再序列化,就是序列化返回的数据,也就是ret -类中需要掌握的几个属性 -page_size:控制每页显示条数 -page_query_param:控制查询第几页的查询参数, -比如page_query_param='xx' -http://127.0.0.1:8000/books/?xx=2 表示查询第二页的数据 -page_size_query_param:控制每页最大显示的条数 -比如page_pagination.page_size_query_param='max' -http://127.0.0.1:8000/books/?xx=2&max=6 表示查询第二页的数据,每页显示6条 -max_page_size:控制每页最大显示的条数 -比如:page_pagination.max_page_size=7 -http://127.0.0.1:8000/books/?max=1000 最多显示7条