Skip to content

Commit 3b96f68

Browse files
committed
docs: add filtered count query example to pagination skill
1 parent 8e3cf6b commit 3b96f68

1 file changed

Lines changed: 42 additions & 0 deletions

File tree

skills/fastsqla-pagination/SKILL.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,48 @@ CustomPaginate = Annotated[
170170
]
171171
```
172172

173+
### Count Query with Filters
174+
175+
Since `query_count_dependency` is a FastAPI dependency, it can accept query parameters and other dependencies. This is useful when the count must reflect the same filters applied to the main query:
176+
177+
```python
178+
from sqlalchemy import func, select
179+
from fastsqla import Session
180+
181+
async def filtered_hero_count(
182+
session: Session,
183+
age: int | None = None,
184+
name: str | None = None,
185+
) -> int:
186+
stmt = select(func.count()).select_from(Hero)
187+
if age is not None:
188+
stmt = stmt.where(Hero.age == age)
189+
if name is not None:
190+
stmt = stmt.where(Hero.name.ilike(f"%{name}%"))
191+
result = await session.execute(stmt)
192+
return cast(int, result.scalar())
193+
194+
FilteredPaginate = Annotated[
195+
PaginateType[HeroModel],
196+
Depends(new_pagination(query_count_dependency=filtered_hero_count)),
197+
]
198+
199+
@app.get("/heroes")
200+
async def list_heroes(
201+
paginate: FilteredPaginate,
202+
age: int | None = None,
203+
name: str | None = None,
204+
) -> Page[HeroModel]:
205+
stmt = select(Hero)
206+
if age is not None:
207+
stmt = stmt.where(Hero.age == age)
208+
if name is not None:
209+
stmt = stmt.where(Hero.name.ilike(f"%{name}%"))
210+
return await paginate(stmt)
211+
```
212+
213+
FastAPI resolves the shared `age` and `name` query parameters in both the endpoint and the count dependency, so the count always matches the filtered results.
214+
173215
## Custom Result Processor
174216

175217
The default `result_processor` is:

0 commit comments

Comments
 (0)