Skip to content

Instantly share code, notes, and snippets.

@Graeme22
Last active September 24, 2025 21:38
Show Gist options
  • Save Graeme22/dd5e880263f9bd2b8438cc9d079f8d38 to your computer and use it in GitHub Desktop.
Save Graeme22/dd5e880263f9bd2b8438cc9d079f8d38 to your computer and use it in GitHub Desktop.
Use SQLModel to query a table using `skip` and `limit` and also get the number of items, using a single query (FastAPI)
from typing import Generic, TypeVar
from pydantic import BaseModel, Field
from sqlmodel import Session, func
M = TypeVar("M", bound=BaseModel)
class QueryResults(BaseModel, Generic[M]):
count: int
items: list[M]
class QueryParams(BaseModel):
limit: int = Field(default=100, gt=0, le=250)
skip: int = Field(default=0, ge=0)
@router.get("/users", response_model=QueryResults[User])
async def get_users(
filters: Annotated[QueryParams, Query()],
session: Annotated[Session, Depends(get_db)],
) -> Any:
result = session.exec(
select(User, func.count(User.id).over().label("total")) # type: ignore
.offset(filters.skip)
.limit(filters.limit)
).all()
users = [user for user, _ in result]
count = result[0][1] if result else 0
return {"count": count, "items": messages}
@RanaUniverse
Copy link

select(User, func.count(User.id).over().label("total")) # type

i don't understand that func.count line how and what does it do

@Graeme22
Copy link
Author

Graeme22 commented Apr 6, 2025

It gets the total number of users in the table. This is useful because the query only returns a subset of the users, often if you're doing pagination like this you want to know how many pages there are in total.

@RanaUniverse
Copy link

Why this comment i do in this page looks differently, it looks like not normal github comment, here is not any emojies, and not such things, why is this.


    with Session(engine) as session:
        statement = (
            select(func.count())
            .select_from(NotePart)
            .where(NotePart.user_id == RanaUniverse_id)
        )

        all_note_count = session.exec(statement).one()
        return all_note_count

what you can say about this, is this ok like this, or it can be more improved, i not understand how does it work as this says .one() as i am wantt to get how many row it has.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment