brsbilgic
brsbilgic

Reputation: 11833

Django REST pagination relative URL instead of absolute URL in ListAPIView

Django Rest Framework generic.ListAPIView sets next&prev parameters to absolute URLs. But I need to set them to relative URLs.

I need to return JSON as below

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

not like this

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

Upvotes: 4

Views: 2124

Answers (3)

iankit
iankit

Reputation: 9342

In the new styles of Pagination, you will have to override get_next_link and get_previous_link methods in the pagination class.

In these methods, use get_full_path() instead of build_absolute_uri().

Although it is always better to be explicit and return absolute URLs in the response, yet there are times when you would want to return relative URI's.

Upvotes: 1

dan-klasson
dan-klasson

Reputation: 14180

Here is the implementation @iankit suggsted:

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)

Upvotes: 5

timop
timop

Reputation: 942

Your're going to have to overwrite rest_framework.pagination.NextPageField.to_native(). And use it in your own custom pagination serializer

Upvotes: 0

Related Questions