Skip to content

Commit f4c4162

Browse files
committed
Update cursor total items docs
1 parent 9519137 commit f4c4162

File tree

2 files changed

+79
-0
lines changed

2 files changed

+79
-0
lines changed

docs/tutorials/cursor-pagination.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,4 +19,14 @@ To use `cursor` you need to import `CursorPage` from `fastapi_pagination.cursor`
1919

2020
```py hl_lines="7"
2121
{! ../docs_src/tutorial/cursor_pagination.py !}
22+
```
23+
24+
25+
## Total items behavior
26+
27+
By default `CursorPage` doesn't include total count of items. If you want to include it, you should customize page
28+
using `UseIncludeTotal` customizer.
29+
30+
```py hl_lines="58-63"
31+
{! ../docs_src/tutorial/cursor_pagination_with_total.py !}
2232
```
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
from typing import TypeVar
2+
3+
from fastapi import FastAPI
4+
from pydantic import BaseModel
5+
from sqlalchemy import create_engine, select
6+
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column
7+
8+
from fastapi_pagination import add_pagination
9+
from fastapi_pagination.cursor import CursorPage
10+
from fastapi_pagination.customization import CustomizedPage, UseIncludeTotal
11+
from fastapi_pagination.ext.sqlalchemy import paginate
12+
13+
app = FastAPI()
14+
add_pagination(app)
15+
16+
engine = create_engine("sqlite:///.db")
17+
18+
19+
class Base(DeclarativeBase):
20+
pass
21+
22+
23+
class User(Base):
24+
__tablename__ = "users"
25+
26+
id: Mapped[int] = mapped_column(primary_key=True)
27+
28+
name: Mapped[str] = mapped_column()
29+
age: Mapped[int] = mapped_column()
30+
31+
32+
class UserOut(BaseModel):
33+
id: int
34+
name: str
35+
age: int
36+
37+
class Config:
38+
orm_mode = True
39+
40+
41+
@app.on_event("startup")
42+
def on_startup():
43+
with engine.begin() as conn:
44+
Base.metadata.drop_all(conn)
45+
Base.metadata.create_all(conn)
46+
47+
with Session(engine) as session:
48+
session.add_all(
49+
[
50+
User(name="John", age=25),
51+
User(name="Jane", age=30),
52+
User(name="Bob", age=20),
53+
],
54+
)
55+
session.commit()
56+
57+
58+
T = TypeVar("T")
59+
60+
CursorWithTotalPage = CustomizedPage[
61+
CursorPage[T],
62+
UseIncludeTotal(True),
63+
]
64+
65+
66+
@app.get("/users")
67+
def get_users() -> CursorWithTotalPage[UserOut]:
68+
with Session(engine) as session:
69+
return paginate(session, select(User).order_by(User.id))

0 commit comments

Comments
 (0)