DRF 光标分页示例 [英] DRF Cursor Pagination example

查看:31
本文介绍了DRF 光标分页示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 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_paramma​​x_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.

这是我目前所拥有的:

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})

我得到一个类似这样的下一个"网址:

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' # '-created' is default

class MyListAPIView(generics.ListAPIView):
    queryset = MyObject.objects.all()
    serializer_class = MySerializer
    pagination_class = CursorSetPagination

这篇关于DRF 光标分页示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆