Created
July 26, 2020 16:17
-
-
Save osw4l/929e9a5ce1a2fc399ba48714ca1a5eba to your computer and use it in GitHub Desktop.
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
class PaginatorMixin(object): | |
min_limit = 1 | |
max_limit = 10 | |
def paginate(self, object_list, page=1, limit=10, **kwargs): | |
try: | |
page = int(page) | |
if page < 1: | |
page = 1 | |
except (TypeError, ValueError): | |
page = 1 | |
try: | |
limit = int(limit) | |
if limit < self.min_limit: | |
limit = self.min_limit | |
if limit > self.max_limit: | |
limit = self.max_limit | |
except (ValueError, TypeError): | |
limit = self.max_limit | |
paginator = Paginator(object_list, limit) | |
try: | |
objects = paginator.page(page) | |
except PageNotAnInteger: | |
objects = paginator.page(1) | |
except EmptyPage: | |
objects = paginator.page(paginator.num_pages) | |
data = { | |
'previous_page': objects.has_previous() and objects.previous_page_number() or None, | |
'next_page': objects.has_next() and objects.next_page_number() or None, | |
'data': list(objects) | |
} | |
return data | |
class CustomViewView(PaginatorMixin, View): | |
def get(self, request): | |
serialized = ResourceSerializer(resources, many=True) | |
return JsonResponse({"resources": self.paginate(serialized.data, page, limit)}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment