Skip to content

Instantly share code, notes, and snippets.

@raffaeletani
Forked from mikeboiko/pagination.py
Last active September 28, 2020 16:40
Show Gist options
  • Save raffaeletani/22752b60d1bde8add69a0655ac15d0fc to your computer and use it in GitHub Desktop.
Save raffaeletani/22752b60d1bde8add69a0655ac15d0fc to your computer and use it in GitHub Desktop.
Django Rest Framework Pagination integration with Vuetable-2
# =======================================================================
# === Description ...: Integrate DRF with VueTable-2
# === Author ........: Mike Boiko
# === Fork by .......: Raffaele Tani, encapsulated pagination in link node, added support for non int indexes
# =======================================================================
# If you want to integrate Django Rest Pagination with VueTable, you must
# change the pagination as shown below:
# Then, in your views.py file, the pagination_class must be set to CustomPagination
# See example below:
# from rest_framework import pagination
# class AuditAPIView(generics.ListAPIView):
# serializer_class = AuditSerializer
# queryset = Audit.objects.all()
# pagination_class = CustomPagination
from rest_framework import pagination, response
class VuetablePagination(pagination.PageNumberPagination):
page_size = 10
page_size_query_param = 'per_page'
# max_page_size = 100
# Paginate in the style defined by vuetable2
def get_paginated_response(self, data):
# Get id's of records in current page
#firstRecord = data[0]['id'] if (data and 'id' in data[0]) else None
#lastRecord = data[-1]['id'] if (data and 'id' in data[0]) else None
firstRecord = (int(self.request.query_params.get('page', 0)) - 1) * int(self.get_page_size(self.request)) + 1
lastRecord = int(self.request.query_params.get('page', 0)) * int(self.get_page_size(self.request))
lastRecord = lastRecord if lastRecord <= self.page.paginator.count else self.page.paginator.count
return response.Response({
'links' : {
'pagination': {
'total': self.page.paginator.count,
'per_page': self.get_page_size(self.request),
'current_page': self.request.query_params.get('page', None),
'last_page': self.page.paginator.num_pages,
'next_page_url': self.get_next_link(),
'previous_page_url': self.get_previous_link(),
'from': firstRecord,
'to': lastRecord,
}
},
'data': data
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment