我們可以發現,而不需要一個解決方案來重新發明輪子:
讓我們對generics
分頁是如何實現一看: django-rest-framework/rest_framework/generics.py。
這正是我們將使用我們的觀點以及!
讓我們假設我們有一個全球性的分頁設置如以下:
settings.py
:
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS':
'rest_framework.pagination.DESIRED_PAGINATION_STYLE',
'PAGE_SIZE': 100
}
爲了不臃腫我們的觀點/視圖集中的代碼,我們可以創建自定義混入存儲我們的分頁代碼:
class MyPaginationMixin(object):
@property
def paginator(self):
"""
The paginator instance associated with the view, or `None`.
"""
if not hasattr(self, '_paginator'):
if self.pagination_class is None:
self._paginator = None
else:
self._paginator = self.pagination_class()
return self._paginator
def paginate_queryset(self, queryset):
"""
Return a single page of results, or `None` if pagination
is disabled.
"""
if self.paginator is None:
return None
return self.paginator.paginate_queryset(
queryset, self.request, view=self)
def get_paginated_response(self, data):
"""
Return a paginated style `Response` object for the given
output data.
"""
assert self.paginator is not None
return self.paginator.get_paginated_response(data)
然後在views.py
:
from rest_framework.settings import api_settings
from rest_framework.views import APIView
from my_app.mixins import MyPaginationMixin
class MyView(APIView, MyPaginationMixin):
queryset = OurModel.objects.all()
serializer_class = OurModelSerializer
pagination_class = api_settings.DEFAULT_PAGINATION_CLASS
# We need to override the get method to insert pagination
def get(self, request):
...
page = self.paginate_queryset(self.queryset)
if page is not None:
serializer = self.serializer_class(page, many=True)
return self.get_paginated_response(serializer.data)
現在我們有一個APIView
與分頁。
'NoneType'對象沒有屬性'paginate_queryset'。即時通訊得到這個錯誤 – Thameem
@Thameem沒有一些代碼來幫助你看看你做了什麼有點困難......如果問題依然存在,考慮在這裏提出一個問題。 –
@感謝您的消息,我錯過了這個響應返回self.get_paginated_response(serializer.data)。謝謝。它的工作現在 – Thameem