Created
February 28, 2018 11:37
-
-
Save srgrn/96b3e2b952fd8d86cd80ae6bc8809eee to your computer and use it in GitHub Desktop.
Django DRF LinkHeaderPagination
This file contains 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
from rest_framework import pagination | |
from rest_framework.response import Response | |
class LinkHeaderPagination(pagination.CursorPagination): | |
def paginate_queryset(self, queryset, request, view=None): | |
try: | |
self.count = queryset.count() | |
except (AttributeError, TypeError): | |
self.count = len(queryset) | |
return super().paginate_queryset(queryset, request, view=None) | |
def get_paginated_response(self, data): | |
next_url = self.get_next_link() | |
previous_url = self.get_previous_link() | |
headers = {} | |
if next_url is not None: | |
headers['XNextLink'] = next_url | |
if previous_url is not None: | |
headers['XPrevLink'] = previous_url | |
if self.count is not None: | |
headers['XTotal-Count'] = self.count | |
return Response(data, headers=headers) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment