From 606e32603e009807fd040d3708f15ac74e537e39 Mon Sep 17 00:00:00 2001 From: Jens Langhammer Date: Sun, 29 Nov 2020 22:14:03 +0100 Subject: [PATCH] api: improve pagination to show relevant data used for interface --- passbook/api/pagination.py | 29 +++++++++++++++++++++++++++++ passbook/policies/api.py | 1 + passbook/root/settings.py | 2 +- 3 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 passbook/api/pagination.py diff --git a/passbook/api/pagination.py b/passbook/api/pagination.py new file mode 100644 index 000000000..9c9ff2759 --- /dev/null +++ b/passbook/api/pagination.py @@ -0,0 +1,29 @@ +"""Pagination which includes total pages and current page""" +from rest_framework import pagination +from rest_framework.response import Response + + +class Pagination(pagination.PageNumberPagination): + """Pagination which includes total pages and current page""" + + def get_paginated_response(self, data): + previous_page_number = 0 + if self.page.has_previous(): + previous_page_number = self.page.previous_page_number() + next_page_number = 0 + if self.page.has_next(): + next_page_number = self.page.next_page_number() + return Response( + { + "pagination": { + "next": next_page_number, + "previous": previous_page_number, + "count": self.page.paginator.count, + "current": self.page.number, + "total_pages": self.page.paginator.num_pages, + "start_index": self.page.start_index(), + "end_index": self.page.end_index(), + }, + "results": data, + } + ) diff --git a/passbook/policies/api.py b/passbook/policies/api.py index f48540bd4..636ff9530 100644 --- a/passbook/policies/api.py +++ b/passbook/policies/api.py @@ -97,3 +97,4 @@ class PolicyBindingViewSet(ModelViewSet): queryset = PolicyBinding.objects.all() serializer_class = PolicyBindingSerializer filterset_fields = ["policy", "target", "enabled", "order", "timeout"] + search_fields = ["policy__name"] diff --git a/passbook/root/settings.py b/passbook/root/settings.py index 3039f371e..81effe556 100644 --- a/passbook/root/settings.py +++ b/passbook/root/settings.py @@ -140,7 +140,7 @@ SWAGGER_SETTINGS = { } REST_FRAMEWORK = { - "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.LimitOffsetPagination", + "DEFAULT_PAGINATION_CLASS": "passbook.api.pagination.Pagination", "PAGE_SIZE": 100, "DEFAULT_FILTER_BACKENDS": [ "rest_framework_guardian.filters.ObjectPermissionsFilter",