跳转至

分页

API 参考:Pagination

分页行为由 ViewSet 的 pagination_class 决定,默认使用 PageNumberPagination。使用说明见 分页。

from srf.paginator import PageNumberPagination
from srf.views import BaseViewSet


class BookViewSet(BaseViewSet):
    queryset = Book.all()  # Tortoise QuerySet
    schema = BookSchema  # Pydantic 模型
    pagination_class = PageNumberPagination

响应结构

list() 返回的对象固定包含四个字段:

{
  "count": 42,
  "next": true,
  "previous": false,
  "results": [{ "id": 1, "title": "..." }]
}

与 DRF 的差异

next / previous 是布尔值,不是下一页/上一页的 URL。前端需要自己拼装页码。

查询参数

参数 默认值 规则
page 1 非整数或小于 1 时回退/夹到 1
page_size 10 非整数时回退为 10,小于 1 时夹到 1,上限为 MAX_PAGE_SIZE(默认 100)
  • 页码超出总页数时返回空 results,count 仍是总记录数。
  • page_size 的上限由类属性 MAX_PAGE_SIZE 控制,子类可以覆盖;构造函数也会把 page / page_size 夹到合法范围。
  • 参数名分别由 PAGE_QUERY_PARAM / PAGE_SIZE_QUERY_PARAM 控制。

分页器 API

BasePagination

Base class for pagination styles (DRF-style).

Custom pagination must subclass this and implement the methods that raise NotImplementedError. Inheritance is the supported extension path.

from_queryset classmethod

from_queryset(queryset: QuerySet[T], request: Request) -> BasePagination

paginate async

paginate(sch_model: type[BaseModel] | None = None) -> PaginationResult

to_dict async

to_dict(sch_model: type[BaseModel] | None = None) -> dict[str, Any]

num_pages

num_pages(total_count: int) -> int

serialize_list

serialize_list(sch_model: type[BaseModel], rows: list[Any]) -> list[dict[str, Any]]

Convert ORM rows to JSON-ready dicts; override for custom list serialization.

options: heading_level: 4 members: - from_queryset - paginate - to_dict - num_pages - serialize_list show_source: false inherited_members: false

自定义分页器应继承 BasePagination 并实现 from_queryset()、paginate()、num_pages()。

PageNumberPagination

PageNumberPagination(queryset: QuerySet[T], page: int = 1, page_size: int = 10)

Bases: BasePagination

A simple page number based style that supports page numbers as query parameters. For example:

/api/users/?page=1 /api/users/?page=2&page_size=100

Invalid or missing parameters fall back to page=1 / page_size=10.

Attributes:

Name Type Description
MAX_PAGE_SIZE int

Upper bound accepted for the page_size query parameter.

PAGE_QUERY_PARAM str

Name of the query parameter carrying the page number.

PAGE_SIZE_QUERY_PARAM str

Name of the query parameter carrying the page size.

queryset

The Tortoise QuerySet being paginated.

page

Current page number (1-based).

page_size

Items per page.

:param queryset: Tortoise ORM queryset :param page: 1-based page number; values below 1 are clamped. :param page_size: Items per page; clamped to 1..MAX_PAGE_SIZE.

MAX_PAGE_SIZE class-attribute instance-attribute

MAX_PAGE_SIZE: int = 100

PAGE_QUERY_PARAM class-attribute instance-attribute

PAGE_QUERY_PARAM: str = 'page'

PAGE_SIZE_QUERY_PARAM class-attribute instance-attribute

PAGE_SIZE_QUERY_PARAM: str = 'page_size'

queryset instance-attribute

queryset = queryset

page instance-attribute

page = max(int(page), 1)

page_size instance-attribute

page_size = min(max(int(page_size), 1), max(MAX_PAGE_SIZE, 1))

from_queryset classmethod

from_queryset(queryset: QuerySet[T], request: Request) -> PageNumberPagination

Parse page and page_size from request; fall back to defaults when invalid.

paginate async

paginate(sch_model: type[BaseModel] | None = None) -> PaginationResult

to_dict async

to_dict(sch_model: type[BaseModel] | None = None) -> dict[str, Any]

num_pages

num_pages(total_count: int) -> int

Return the total number of pages (empty results still have one page).

serialize_list

serialize_list(sch_model: type[BaseModel], rows: list[Any]) -> list[dict[str, Any]]

Convert ORM rows to JSON-ready dicts; override for custom list serialization.

options: heading_level: 4 members: - init - MAX_PAGE_SIZE - PAGE_QUERY_PARAM - PAGE_SIZE_QUERY_PARAM - from_queryset - paginate - to_dict - num_pages show_source: false inherited_members: false

PaginationResult

Bases: BaseModel

count instance-attribute

count: int

next instance-attribute

next: bool

previous instance-attribute

previous: bool

results instance-attribute

results: list[Any]

options: heading_level: 4 members: true show_source: false inherited_members: false

PaginationResult 的字段对应响应中的四个键。

serialize_page

serialize_page(schema: type[BaseModel], rows: list[Any]) -> list[dict[str, Any]]

Serialize ORM rows through a Reader/Writer schema for list responses.

Uses a cached TypeAdapter so schema structure is not re-built per row. Row data is still validated on every call; only the adapter is reused.

options: heading_level: 4 show_source: false

serialize_page() 使用按 Schema 缓存的 TypeAdapter(list[schema]),适合在自定义分页器中复用。