Skip to content

Instantly share code, notes, and snippets.

@mikeboiko
Last active November 22, 2020 14:07
Show Gist options
  • Save mikeboiko/55c12de45f2a606b777d7507eba8b399 to your computer and use it in GitHub Desktop.
Save mikeboiko/55c12de45f2a606b777d7507eba8b399 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
# =======================================================================
# 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 CustomPagination(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
return response.Response({
'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(),
'first': firstRecord,
'last': lastRecord,
},
'data': data
})
@mikeboiko
Copy link
Author

@raffaeletani, glad this was helpful!
I haven't used this code for a couple of years now, but I'll keep your comments in mind next time I'm working on a DRF/Vue project.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment