Answered: Simplest unpaginated page equivalent? #666
-
Hi everyone, I have the rather odd problem of needing to get rid of pagination, perhaps temporarily, without breaking existing frontend. So we want to have I can go through and write from typing import Generic, TypeVar, Sequence
from pydantic.generics import GenericModel
T = TypeVar("T")
class UnpaginatedPage(GenericModel, Generic[T]):
items: Sequence[T] And this works great, except one issue. Let's say we're using SQLModel, and we have a different response model than the database object, itself. We want to convert to the This doesn't do that conversion. I've tried setting Curious if anyone knows the answer to this. I feel like it's a pretty short bit of code to make it work. For now, I'm manually converting my database objects to their read variants. Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 6 replies
-
Hi @gitpushdashf, I hope the example below will help you: from typing import Any, Generic, List, Optional, TypeVar
from fastapi import FastAPI
from pydantic import BaseModel
from pydantic.generics import GenericModel
from sqlalchemy import select
from sqlmodel import Field, Session, SQLModel, create_engine
engine = create_engine("sqlite:///database.db")
class User(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
email: str
SQLModel.metadata.drop_all(engine)
SQLModel.metadata.create_all(engine)
app = FastAPI()
@app.on_event("startup")
async def on_startup() -> None:
with Session(engine) as session:
session.add(
User(
id=1,
name="John Doe",
email="[email protected]",
),
)
session.commit()
class UserOut(BaseModel):
id: int
name: str
email: str
class Config:
orm_mode = True
T = TypeVar("T")
class GenericListSchema(GenericModel, Generic[T]):
items: List[T]
@app.get("/users", response_model=GenericListSchema[UserOut])
async def get_users() -> Any:
with Session(engine) as session:
users = session.scalars(select(User)).all()
return {"items": users} |
Beta Was this translation helpful? Give feedback.
Hi @gitpushdashf,
I hope the example below will help you: