DRF分页器

DRF分页器

1.普通分页器

​ 主要的四个属性

#一页返回的数据数,必传
paginate.page_size = 2
#自定义一页要返回的数据数,以get的形式传,key为size
paginate.page_size_query_param = 'size'
#自定义页码数的名字为p,默认为page
paginate.page_query_param = 'p'
#一页显示最大的数据数
paginate.max_page_size = 3

​ 序列化数据的类

class BookXLH(serializers.ModelSerializer):
    class Meta:
        model = models.Book
        fields = '__all__'

​ 在视图行数中的使用

from rest_framework.pagination import PageNumberPagination
class Books(ModelViewSet,APIView):
     def get_all_book(self,request,*args,**kwargs):
         books = models.Book.objects.all()
         paginate = PageNumberPagination()
         paginate.page_size = 2
         paginate.page_size_query_param = 'size'
         paginate.page_query_param = 'p'
         paginate.max_page_size = 3
         paginate_list = paginate.paginate_queryset(books,request,self)
         books_res = BookXLH(instance=paginate_list,many=True)
         response = {'msg':books_res.data}
         return Response(response)

​ 路由

url(r'^books/$',views.Books.as_view({'get':'get_all_book'}))

2.偏移分页器

​ 主要的属性

#每页显示的数据条数
pagination.default_limit = 4
#要偏移的标杆,在前端以get的形式传,key为offset('可修改')
pagination.offset_query_param = 'offset'
#偏移量,,在前端以get的形式传,key为limit('可修改')
pagination.limit_query_param = 'limit'
#一页最大的显示条数
pagination.max_limit = 2

​ 序列化的类

class BookXLH(serializers.ModelSerializer):
    class Meta:
        model = models.Book
        fields = '__all__'

​ 在视图函数中的使用

from rest_framework.pagination import LimitOffsetPagination
class Books(ModelViewSet,APIView):
     def get_all_book(self,request,*args,**kwargs):
         books = models.Book.objects.all().order_by('nid')
         pagination = LimitOffsetPagination()

         pagination.default_limit = 4
         pagination.offset_query_param = 'offset'
         pagination.limit_query_param = 'limit'
         pagination.max_limit = 2
         paginate_list = pagination.paginate_queryset(books,request,self)

         books_res = BookXLH(instance=paginate_list,many=True)
         response = {'msg':books_res.data}
         return Response(response)

3.加密的分页

​ 主要的属性

#按nid排序
page.ordering = 'nid'
#查询的key值
cursor_query_param = 'cursor'
#每页显示多少条
page_size = api_settings.PAGE_SIZE

​ 序列化的类

class BookXLH(serializers.ModelSerializer):
    class Meta:
        model = models.Book
        fields = '__all__'

​ 在视图函数中的使用

from rest_framework.pagination import CursorPagination
class Books(ModelViewSet,APIView):
    def get_all_book(self,request,*args,**kwargs):
        books = models.Book.objects.all()
        paginate = CursorPagination()
        paginate.page_size=2
        paginate.ordering = 'nid'
        paginate_list = paginate.paginate_queryset(books,request,self)
        books_res = BookXLH(instance=paginate_list,many=True)
        response = {'msg':books_res.data}
        return paginate.get_paginated_response(books_res.data)
posted @ 2018-12-18 18:36  周建豪  阅读(339)  评论(0编辑  收藏  举报