djagno + rest_framework2.X pagination實作方法
Django 提供了一種方便整合分頁的功能
from django.core.paginator import Paginator
rest_framework也提供相對應的功能
from rest_framework import pagination注意:rest_framework 3 沒提供pagination的功能了
功能:
透過”Previous/Next”的links來整合多筆資料
逕而達到分頁效果。
原理:
Paginator 傳入data,以及每一頁要呈現的資料數量取得實體
在將Query parames取得當前page number
最後透過page number去取得該page的資料
PaginationSerializer
將先後頁及筆數同時序列化
fields:
count
next
previous程式:
views.py
cars = Car.objects.filter(color="red").order_by('-date')
cars = paginationTools(objects_list=cars, pre_page=9, page_number=request.QUERY_PARAMS.get('page'))
serializer_context = {'request': request}
serializer = PaginatedCarsSerializer(data=scenes, context=serializer_context)
return Response(serializer.data,status=status.HTTP_200_OK)
pre_page意思是一分頁要幾個item
page_number則是取得現在是要取得第幾頁的內容 serializer.py
class PaginatedCarsSerializer(pagination.PaginationSerializer):
#自定義欄位
start_index = serializers.SerializerMethodField('getStartIndex')
end_index = serializers.SerializerMethodField('getEndIndex')
page_count = serializers.ReadOnlyField(source='paginator.num_pages')
#Reda only use "source="XXXX"
current_index = serializers.ReadOnlyField(source='number')
class Meta:
#指定serializer class
object_serializer_class = CarSerializer
def getStartIndex(self, obj):
return obj.start_index()
def getEndIndex(self, obj):
return obj.end_index()
class CarSerializer(serializers.ModelSerializer):
""" Session Serializer """
class Meta:
model = EventScenes
fields = ['name', 'image', 'id', 'description', 'color', 'place']
mytools.py
def paginationTools(objects_list, pre_page, page_number):
paginator = Paginator(objects_list, pre_page)
try:
result = paginator.page(page_number)
except PageNotAnInteger:
result = paginator.page(1)
except EmptyPage:
result = paginator.page(paginator.num_pages)
except InvalidPage:
result = paginator.page(1)
return result
這裡基本是封裝了我的Django pagination的方法其中做了try catch
訂閱:
張貼留言
(
Atom
)
技術提供:Blogger.
沒有留言 :
張貼留言