foo*_*bar 2 pagination django-rest-framework
我正在尝试使用DRF设置CursorPagination以获取事务记录列表(按创建日期排序).我无法弄清楚如何进行初始请求,因为我在那个阶段还不知道光标.令人惊讶的是,我找不到这样的例子.
另外,有没有办法用CursorPagination设置每个请求的页面大小,PageNumberPagination有page_size_query_param和max_page_size,它们不适用于CursorPagination.
这是我到目前为止所拥有的:
class RecordPagination(pagination.CursorPagination):
page_size = 10
class RecordsOverview(generics.ListAPIView):
serializer_class = RecordSerializer
logging_methods = ['GET']
queryset = Record.objects.all()
pagination_class = RecordPagination
# Note: this is my way to dynamically set the page size,
# it is totally hacky, so I'm open to suggestions
# is_number method is left out for brevity
def get(self, request, *args, **kwargs):
page_size = request.GET.get('page_size', '')
if self.is_number(page_size) and int(page_size) > 0:
self.paginator.page_size = int(page_size)
return self.list(request, *args, **kwargs)
Run Code Online (Sandbox Code Playgroud)
然后在我的测试中我做了一个GET请求:
response = self.client.get(GET_RECORDS_URL, data={'page_size': 2})
Run Code Online (Sandbox Code Playgroud)
我找回一个看起来像这样的"下一个"网址:
http://testserver/api/v1/records/?cursor=cj0xJnA9MjAxNy0wOS0yMCsxNCUzQTM0JTNBNDkuNjUxMDU4JTJCMDAlM0EwMA%3D%3D&page_size=2
Run Code Online (Sandbox Code Playgroud)
如果我得到(next_url),我将获得下一个记录,这次我不必传递data = {'page_size':2}.
如果我能以更清洁,更一致的方式完成所有这些工作,请告诉我.
这就是我如何使用CursorPagination而没有任何复杂情况:
from rest_framework.pagination import CursorPagination
class CursorSetPagination(CursorPagination):
page_size = 5
page_size_query_param = 'page_size'
ordering = '-timestamp' # '-creation' is default
class MyListAPIView(generics.ListAPIView):
queryset = MyObject.objects.all()
serializer_class = MySerializer
pagination_class = CursorSetPagination
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1969 次 |
| 最近记录: |