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?
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,
})
#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
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With