Last active
November 22, 2020 14:07
-
-
Save mikeboiko/55c12de45f2a606b777d7507eba8b399 to your computer and use it in GitHub Desktop.
Django Rest Framework Pagination integration with Vuetable-2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ======================================================================= | |
# === 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 | |
}) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@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.