From 7892c8358e9733f7e2c565dad898b2c364bf09fd Mon Sep 17 00:00:00 2001 From: Stepan Date: Sun, 28 Dec 2025 16:33:13 +0100 Subject: [PATCH] Fixed pagination and average score in swagger --- project/pagination.py | 32 ++++++++++++++++++++++++++++++++ project/settings/base.py | 2 +- publications/serializers.py | 2 ++ 3 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 project/pagination.py diff --git a/project/pagination.py b/project/pagination.py new file mode 100644 index 0000000..5b6fe5e --- /dev/null +++ b/project/pagination.py @@ -0,0 +1,32 @@ +from rest_framework.pagination import PageNumberPagination +from rest_framework.response import Response +import math + +class CustomPagination(PageNumberPagination): + page_size = 20 + page_size_query_param = 'limit' + + def get_paginated_response(self, data): + total_items = self.page.paginator.count + total_pages = math.ceil(total_items / self.page_size) + + return Response({ + 'count': total_items, + 'page_size': self.page_size, + 'page': self.page.number, + 'total_pages': total_pages, + 'results': data + }) + + # drf spectacular swagger + def get_paginated_response_schema(self, schema): + return { + 'type': 'object', + 'properties': { + 'count': {'type': 'integer'}, + 'page': {'type': 'integer'}, + 'page_size': {'type': 'integer'}, + 'total_pages': {'type': 'integer'}, + 'results': schema, + }, + } \ No newline at end of file diff --git a/project/settings/base.py b/project/settings/base.py index c5985fa..8461541 100644 --- a/project/settings/base.py +++ b/project/settings/base.py @@ -75,7 +75,7 @@ SPECTACULAR_SETTINGS = { CORS_ALLOW_ALL_ORIGINS = True REST_FRAMEWORK = { - 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', + 'DEFAULT_PAGINATION_CLASS': 'project.pagination.CustomPagination', 'PAGE_SIZE': 20, 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', diff --git a/publications/serializers.py b/publications/serializers.py index 050d044..4a4b7d6 100644 --- a/publications/serializers.py +++ b/publications/serializers.py @@ -1,5 +1,6 @@ from rest_framework import serializers from rest_framework.exceptions import ValidationError +from drf_spectacular.utils import extend_schema_field from users.serializers import PublicUserSerializer from .models import Publication, Rating, Category @@ -14,6 +15,7 @@ class PublicationSerializer(serializers.ModelSerializer): user_detail = PublicUserSerializer(source="user", read_only=True) average_score = serializers.SerializerMethodField(read_only=True) + @extend_schema_field(serializers.FloatField()) def get_average_score(self, obj): return getattr(obj, 'average_score', 0)