Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 781
baermathias Avatar asked Sep 18 '25 14:09

baermathias


2 Answers

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,
        })
like image 78
Gorkhali Khadka Avatar answered Sep 21 '25 02:09

Gorkhali Khadka


#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
        })
like image 30
Caleepso Avatar answered Sep 21 '25 04:09

Caleepso