Django休息PageNumber分页

时间:2017-04-26 22:58:43

标签: python django pagination django-rest-framework

我有一个简单的django休息框架的分页类:

class StandardResultsSetPagination(PageNumberPagination):
    page_size = 100
    page_size_query_param = 'page_size'
    max_page_size = 1000

# Create your views here.
class ResultSet(generics.ListAPIView):
    queryset = Result.objects.all()
    serializer_class = ResultSetSerializer
    pagination_class = StandardResultsSetPagination

此类目前返回包含'prev''next'个键的dict,其中包含带有下一页和prev页面的URL。我想要实现的是'prev''next'只返回页码而不是整个网址。

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:3)

您可以覆盖PageNumberPagination的get_next_linkget_previous_link 默认为:

   def get_next_link(self):
        if not self.page.has_next():
            return None
        url = self.request.build_absolute_uri()
        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.build_absolute_uri()
        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)

您可以覆盖:

class StandardResultsSetPagination(PageNumberPagination):
    page_size = 100
    page_size_query_param = 'page_size'
    max_page_size = 1000

    def get_next_link(self):
        if not self.page.has_next():
            return None
        page_number = self.page.next_page_number()
        return page_number

    def get_previous_link(self):
        if not self.page.has_previous():
            return None
        page_number = self.page.previous_page_number()
        return page_number