From 8089a2fdcc7be9dece2399f948891728ced853f1 Mon Sep 17 00:00:00 2001 From: borzechof99 <borzechof99@mi.fu-berlin.de> Date: Mon, 21 Jun 2021 15:51:01 +0200 Subject: [PATCH] Add Pagination to small-sport-list --- unisportomat/quiz/pagination.py | 1 + unisportomat/quiz/views.py | 25 +++++++++++++++++++++++-- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/unisportomat/quiz/pagination.py b/unisportomat/quiz/pagination.py index 385a061..058ca4b 100644 --- a/unisportomat/quiz/pagination.py +++ b/unisportomat/quiz/pagination.py @@ -5,6 +5,7 @@ or be given globally via settings.py. """ from rest_framework.pagination import PageNumberPagination +from rest_framework.response import Response class PageNumberWithPageSizePagination(PageNumberPagination): diff --git a/unisportomat/quiz/views.py b/unisportomat/quiz/views.py index 7207d88..275d97a 100644 --- a/unisportomat/quiz/views.py +++ b/unisportomat/quiz/views.py @@ -7,6 +7,8 @@ from rest_framework import viewsets from rest_framework.views import APIView from rest_framework.response import Response from django.http import JsonResponse +from .pagination import PageNumberWithPageSizePagination + from .serializers import ( SmallSportListSerializer, SportListSerializer, @@ -63,11 +65,30 @@ class SmallSportListView(viewsets.ViewSet): # GET for api/admin/sport/ def list(self, request): + paginator = PageNumberWithPageSizePagination() + """ + Comments on Pagination: + Every list that needs to be paginated needs a paginator. + Here, the Paginator object is created in the GET call. + The Queryset which is supposed to be paginated needs to be run through the function: + + > new_queryset = paginator.paginate_queryset(complete_queryset, request) + + The new_queryset is a List, not a Manager, so it can be directly iterated upon. + After the data has been worked on and run through the Serializer as normal, + instead of returning Result(data), the paginator needs to be used again so it can add its page metadata: + + > return paginator.get_paginated_response(serializer.data) + + This function already returns a fully valid Response, so it can be directly returned. + """ + sports = Sport.objects.all() + sports = paginator.paginate_queryset(sports, request) criteria = Criterion.objects.all() is_filled_tuples = [] - for sport in sports.iterator(): + for sport in sports: filled_criteria_pks = [] @@ -88,7 +109,7 @@ class SmallSportListView(viewsets.ViewSet): serializer = SmallSportListSerializer(is_filled_tuples) - return Response(serializer.data) + return paginator.get_paginated_response(serializer.data) # POST for api/admin/sport/ def create(self, request): -- GitLab