DRF光标分页示例 [英] DRF Cursor Pagination example
问题描述
我正在尝试使用DRF设置CursorPagination以获得交易记录列表(按创建日期排序). 我不知道如何执行初始请求,因为在此阶段我还不知道游标.令人惊讶的是,我找不到这样的例子.
I'm trying to setup CursorPagination with DRF for a list of transaction records (ordered by creation date). I can't figure out how to do an initial request because I don't know the cursor yet at that stage. Surprisingly, I can't find an example of this.
此外,还有一种方法可以使用CursorPagination设置每个请求的页面大小,PageNumberPagination具有 page_size_query_param 和 max_page_size ,而CursorPagination则不存在.
Also, is there a way to set the page size per request with CursorPagination, the PageNumberPagination have page_size_query_param and max_page_size and they aren't there for CursorPagination.
这是我到目前为止的内容:
Here's what I have so far:
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)
然后在我的测试中,我执行GET请求:
Then in my test I do a GET request:
response = self.client.get(GET_RECORDS_URL, data={'page_size': 2})
我返回一个看起来像这样的下一个" URL:
I get back a 'next' url that looks something like this:
http://testserver/api/v1/records/?cursor=cj0xJnA9MjAxNy0wOS0yMCsxNCUzQTM0JTNBNDkuNjUxMDU4JTJCMDAlM0EwMA%3D%3D&page_size=2
如果我 get(next_url),我将获得下一条记录,这一次,我不必传递 data = {'page_size':2} >.
If I do get(next_url) I will get the next records OK, and this time I don't have to pass data={'page_size': 2}.
请让我知道是否可以用一种更清洁,更一致的方式来完成所有这些工作.
Please, let me know if I can do all of this in a cleaner and more consistent way.
推荐答案
这是我使用CursorPagination的方式,没有任何复杂性:
This is how I use CursorPagination without any complications:
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
这篇关于DRF光标分页示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!