使用分頁(yè)器大大提升了程序性能,而分頁(yè)器組件又為我們封裝好了,讓開(kāi)發(fā)變得更輕松。
一 簡(jiǎn)單分頁(yè)(查看第n頁(yè),每頁(yè)顯示n條)
from rest_framework.pagination import PageNumberPagination
# 一 基本使用:url=url=http://127.0.0.1:8000/pager/?page=2&size=3,size無(wú)效
class Pager(APIView):
def get(self,request,*args,**kwargs):
# 獲取所有數(shù)據(jù)
ret=models.Book.objects.all()
# 創(chuàng)建分頁(yè)對(duì)象
page=PageNumberPagination()
# 在數(shù)據(jù)庫(kù)中獲取分頁(yè)的數(shù)據(jù)
page_list=page.paginate_queryset(ret,request,view=self)
# 對(duì)分頁(yè)進(jìn)行序列化
ser=BookSerializer1(instance=page_list,many=True)
return Response(ser.data)
# 二 自定制 url=http://127.0.0.1:8000/pager/?page=2&size=3
# size=30,無(wú)效,最多5條
class Mypage(PageNumberPagination):
page_size = 2
page_query_param = 'page'
# 定制傳參
page_size_query_param = 'size'
# 最大一頁(yè)的數(shù)據(jù)
max_page_size = 5
class Pager(APIView):
def get(self,request,*args,**kwargs):
# 獲取所有數(shù)據(jù)
ret=models.Book.objects.all()
# 創(chuàng)建分頁(yè)對(duì)象
page=Mypage()
# 在數(shù)據(jù)庫(kù)中獲取分頁(yè)的數(shù)據(jù)
page_list=page.paginate_queryset(ret,request,view=self)
# 對(duì)分頁(yè)進(jìn)行序列化
ser=BookSerializer1(instance=page_list,many=True)
# return Response(ser.data)
# 這個(gè)也是返回Response對(duì)象,但是比基本的多了上一頁(yè),下一頁(yè),和總數(shù)據(jù)條數(shù)(了解即可)
return page.get_paginated_response(ser.data)
setting里
REST_FRAMEWORK = {
# 每頁(yè)顯示兩條
'PAGE_SIZE':2
}
路由:
url(r'^pager/$', views.Pager.as_view()),
序列化組件中
class BookSerializer1(serializers.ModelSerializer):
class Meta:
model=models.Book
exclude=('authors',)
二 偏移分頁(yè)(在第n個(gè)位置,向后查看n條數(shù)據(jù))
# http://127.0.0.1:8000/pager/?offset=4&limit=3
from rest_framework.pagination import LimitOffsetPagination
# 也可以自定制,同簡(jiǎn)單分頁(yè)
class Pager(APIView):
def get(self,request,*args,**kwargs):
# 獲取所有數(shù)據(jù)
ret=models.Book.objects.all()
# 創(chuàng)建分頁(yè)對(duì)象
page=LimitOffsetPagination()
# 在數(shù)據(jù)庫(kù)中獲取分頁(yè)的數(shù)據(jù)
page_list=page.paginate_queryset(ret,request,view=self)
# 對(duì)分頁(yè)進(jìn)行序列化
ser=BookSerializer1(instance=page_list,many=True)
# return page.get_paginated_response(ser.data)
return Response(ser.data)
三 CursorPagination(加密分頁(yè),只能看上一頁(yè)和下一頁(yè),速度快)
from rest_framework.pagination import CursorPagination
# 看源碼,是通過(guò)sql查詢,大于id和小于id
class Pager(APIView):
def get(self,request,*args,**kwargs):
# 獲取所有數(shù)據(jù)
ret=models.Book.objects.all()
# 創(chuàng)建分頁(yè)對(duì)象
page=CursorPagination()
page.ordering='nid'
# 在數(shù)據(jù)庫(kù)中獲取分頁(yè)的數(shù)據(jù)
page_list=page.paginate_queryset(ret,request,view=self)
# 對(duì)分頁(yè)進(jìn)行序列化
ser=BookSerializer1(instance=page_list,many=True)
# 可以避免頁(yè)碼被猜到
return page.get_paginated_response(ser.data)