在响应中包含Content-Range
标题:
您只需要创建一个标题字典,Content-Range
其键和值作为返回的项目数以及存在的总项目数。
例如:
class ContentRangeHeaderPagination(pagination.PageNumberPagination):
"""
A custom Pagination class to include Content-Range header in the
response.
"""
def get_paginated_response(self, data):
"""
Override this method to include Content-Range header in the response.
For eg.:
Sample Content-Range header value received in the response for
items 11-20 out of total 50:
Content-Range: items 10-19/50
"""
total_items = self.page.paginator.count # total no of items in queryset
item_starting_index = self.page.start_index() - 1 # In a page, indexing starts from 1
item_ending_index = self.page.end_index() - 1
content_range = 'items {0}-{1}/{2}'.format(item_starting_index, item_ending_index, total_items)
headers = {'Content-Range': content_range}
return Response(data, headers=headers)
假设这是收到的标头:
Content-Range: items 0-9/50
这表示前 10 个项目被退回 total 50
。
注意:如果计算总计很昂贵,您也可以使用*
代替。total_items
Content-Range: items 0-9/* # Use this if total is expensive to calculate