【问题标题】:How do you get the current cursor with CursorPagination?您如何使用 CursorPagination 获取当前光标?
【发布时间】:2020-02-01 04:28:07
【问题描述】:

默认情况下,CursorPagination 为您提供下一个和上一个光标。有没有办法获取当前光标?

【问题讨论】:

  • 这没有任何意义。当前页面是结果列表。光标在那里做什么?
  • @DanielRoseman 转到下一个光标并返回到前一个光标将为您提供“当前光标”。这将是一种保存当前位置的方法。这与获取最新的结果列表不同。
  • 但这不只是当前网址吗?
  • @DanielRoseman 不。也许我没有正确解释。这是一个例子。例如在当前 URL 中,您会看到 5 个帖子 [1, 2, 3, 4, 5]。一周后,又有100个帖子。当前 URL 将为您提供 [101, 102, 103, 104, 105] 但您想从上次中断的地方继续。
  • 对不起,我还是不明白。为什么当前 URL 会给你 101,... 而不是 1,...?

标签: django django-rest-framework pagination


【解决方案1】:

CusorPagination 类只是从查询字符串中读取值并对其进行解码以供内部使用。如果您想知道刚刚发出的请求的当前位置,您可以简单地做同样的事情。由于分页器实例在使用后被丢弃,因此您无法偷看。

即使可以,您也会得到“解码”的光标值,您必须重新编码才能稍后再次发送。

# from rest_framework/pagination.py@CursorPagination.paginate_queryset
encoded = request.query_params.get(self.cursor_query_param)

# read it yourself somewhere in your view/viewset
current_value = request.query_params.get('cursor')

如果您想更改一般行为,只需进行自定义实现并返回附加字段。在视图上将其设置为您的pagination_class(如果它是全局的,则在设置中)。

未测试示例代码:

class FancyCursorPagination(CusorPagination):

    def get_paginated_response(self, data):
        return Response(OrderedDict([
            ('next', self.get_next_link()),
            ('previous', self.get_previous_link()),
            ('current', self.get_current_link()),
            ('results', data)
        ]))

    def get_current_link(self):
        """ 
        Return a link to the current position. 
           - self.cursor set in the paginate_queryset() method.
        To return only the query parameter in this field, use:
           - return request.query_params.get(self.cursor_query_param, None)
        """
        if self.cursor:
            return self.encode_cursor(self.cursor)
        else:
            # cursor will be None on the first call
            return None

    def get_paginated_response_schema(self, schema):
        new_schema = super().get_paginated_response_schema(schema)
        new_schema["properties"]["current"] = {
            "type": "string", 
            "nullable": True
        }
        return new_schema

class MyApiView(APIView):
    pagination_class = FancyCursorPagination

【讨论】:

  • self.encode_cusor(self.cursor) 会抛出错误,因为它没有偏移量。如果你给它一个 0 偏移量,它会给你一个空光标。你可以做这样的事情,但有更多的边缘情况需要处理......Cursor(offset=0,reverse=True,position=self._get_position_from_instance(self.page[-1], self.ordering))
  • 啊,我明白了。我没有考虑第一个请求(没有给出光标)。在这种情况下,self.cusor 将为无。我会编辑这个问题,但它仍然未经测试:D
猜你喜欢
  • 1970-01-01
  • 2011-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多