schon/evibes/pagination.py
fureunoir b6d38d07e5 - Improve pagination logic: add default and validation for page size, fix get_paginated_response behavior.
- Update type annotations in `check_translated` command for app config handling.
- Pin and upgrade dependencies in `pyproject.toml` for consistency and latest features.
2025-12-25 14:50:37 +03:00

74 lines
2.6 KiB
Python

from typing import Any
from django.core.paginator import Paginator
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
class CustomPagination(PageNumberPagination):
page_size_query_param: str = (
"page_size" # name of the query parameter, you can use any
)
def get_paginated_response(self, data: list[dict[Any, Any]]) -> Response:
if not self.page_size:
self.page_size = 88
if not 1 <= self.page_size <= 255:
raise ValueError("Page size must be between 1 and 255")
if not self.page:
paginator = Paginator(data, self.page_size)
self.page = paginator.page(1)
return Response(
{
"links": {
"forward": self.get_next_link(),
"backward": self.get_previous_link(),
},
"counts": {
"total_pages": self.page.paginator.num_pages,
"page_size": self.page_size,
"total_items": self.page.paginator.count,
},
"data": data,
}
)
def get_paginated_response_schema(self, schema: dict[str, Any]) -> dict[str, Any]:
return {
"type": "object",
"properties": {
"links": {
"type": "object",
"properties": {
"forward": {
"type": "string",
"nullable": True,
"format": "uri",
"description": "URL to the next page",
},
"backward": {
"type": "string",
"nullable": True,
"format": "uri",
"description": "URL to the previous page",
},
},
},
"total_pages": {
"type": "integer",
"example": 10,
"description": "Total number of pages",
},
"page_size": {
"type": "integer",
"example": 10,
"description": "Number of items per page",
},
"total_items": {
"type": "integer",
"example": 100,
"description": "Total number of items",
},
"data": schema,
},
}