Last active
September 24, 2025 21:38
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
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.