sunwarr10r
sunwarr10r

Reputation: 4787

Django rest framework: custom pagination next/previous links

In the backend as the DEFAULT_PAGINATION_CLASS I am using the built-in PageNumberPagination. Due to the reason that I use vue.js with fetch, I don't need to pass the whole url like provided by django-rest-framework:

"count": 5,
"next": "http://127.0.0.1:8000/api/something/?page=2",
"previous": null

but only the part after the base url, e.g.:

/api/something/?page=2

or just the page number, so I could build my own endpoint e.g.:

if (!pageNumber) {
  let endpoint = "/api/something/"
} else {
  let endpoint = "/api/something/" + "?page=" + pageNumber;
}

What is the right way to do pagination with django and a JavaScript framework like vue using bootstraps pagination component?

Upvotes: 4

Views: 2253

Answers (3)

Denis
Denis

Reputation: 1258

We can subclass PageNumberPagination and override get_next_link() and get_previous_link() methods to add domain different from one in request object:

url = self.request.build_absolute_uri('https://front-end-domain.com')`

From build_absolute_uri() docs

Upvotes: 0

Caleepso
Caleepso

Reputation: 13

#it is your pagination.py
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response

class MyFavoritePagination(PageNumberPagination):
    def get_paginated_response(self, data):
        nl = self.get_next_link()
        pl = self.get_previous_link()
        return Response({
            'links': {
                'next': nl[nl.find("/api") : ] if nl is not None else None,
                'previous': pl[pl.find("/api") : ] if pl is not None else None
            },
            'count': self.page.paginator.count,
            'results': data
        })

Upvotes: 1

Gorkhali Khadka
Gorkhali Khadka

Reputation: 835

Overwrite your pagination response in views change what ever you want.

 def get_paginated_response(self, data):
        return Response({
            'links': {
                'next': self.get_next_link(),
                'previous': self.get_previous_link()
            },
            'current_page': int(self.request.query_params.get('page', 1)),
            'total': self.page.paginator.count,
            'per_page': self.page_size,
            'total_pages': round(self.page.paginator.count/self.page_size, 1),
            'data': data,
        })

Upvotes: 2

Related Questions