gpt4 book ai didi

Django REST分页相对URL而不是ListAPIView中的绝对URL

转载 作者:行者123 更新时间:2023-12-01 12:38:54 27 4
gpt4 key购买 nike

Django Rest Framework generic.ListAPIView 将 next&prev 参数设置为绝对 URL。但我需要将它们设置为相对 URL。

我需要返回 JSON 如下

# {'count': 4, 'next': '?page=2', 'previous': None, 'results': [u'john', u'paul']}

不是这样
# {'count': 4, 'next': 'http://testserver/foobar?page=2', 'previous': None, 'results': [u'john', u'paul']}

最佳答案

这是@iankit建议的实现:

from rest_framework.utils.urls import remove_query_param, replace_query_param
class LeadListPagination(PageNumberPagination):
page_size = 15

def get_next_link(self):
if not self.page.has_next():
return None
url = self.request.get_full_path()
page_number = self.page.next_page_number()
return replace_query_param(url, self.page_query_param, page_number)

def get_previous_link(self):
if not self.page.has_previous():
return None
url = self.request.get_full_path()
page_number = self.page.previous_page_number()
if page_number == 1:
return remove_query_param(url, self.page_query_param)
return replace_query_param(url, self.page_query_param, page_number)

关于Django REST分页相对URL而不是ListAPIView中的绝对URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26895616/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com