默认情况下,CursorPagination为您提供下一个和上一个光标。有没有办法获取当前光标?
答案 0 :(得分:0)
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