DRF分頁器
阿新 • • 發佈:2018-12-18
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)