Separate SQLModel Classes for Table, Create, Update and Read Keep Validation Honest
One SQLModel class can be both a database table and an API schema, but each operation needs different rules: a client must not send the id, an update makes every field optional, a list response adds pagination. Splitting the entity into a shared base plus one class per role keeps those rules explicit instead of loosening one class until it fits all cases.
One Base, One Class per Role
class BookBase(SQLModel): # shared fields and constraints
title: str = Field(min_length=1, max_length=200)
isbn: str = Field(min_length=10, max_length=13)
price: float | None = Field(default=None, ge=0)
class Book(BookBase, table=True): # the table: server-managed fields
id: int | None = Field(default=None, primary_key=True)
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
class BookCreate(BookBase): pass # POST body: no id, no timestamps
class BookUpdate(SQLModel): # PATCH body: everything optional
title: str | None = Field(default=None, min_length=1, max_length=200)
price: float | None = Field(default=None, ge=0)
class BookList(SQLModel): # paginated response
items: list[Book]
total: int
skip: int
limit: int
For a PATCH, apply only the fields the client actually sent: book.sqlmodel_update(data.model_dump(exclude_unset=True)).
Pitfalls in the Constraints
datetime.utcnowis deprecated since Python 3.12 and returns a naive datetime; usedatetime.now(timezone.utc).updated_atwith only adefault_factoryis set at creation and never again: update it in the service layer, or with anonupdatecolumn argument.class Config: schema_extrais Pydantic v1 syntax; with Pydantic v2 usemodel_config = {"json_schema_extra": {"examples": [...]}}.
References
- FastAPI MOC - hub for FastAPI notes.
- Only the Route Layer of a FastAPI App Should Raise HTTP Errors - the service layer that applies these models.
- SQLModel documentation: Multiple Models with FastAPI - the base/table/create/read pattern.
- SQLModel documentation: Update Data with FastAPI -
exclude_unsetandsqlmodel_update. - Pydantic documentation: Migration guide -
Configtomodel_config.
Review cards
Flashcard Why give an entity separate table, Create and Update classes instead of one SQLModel class?
Each role has different rules: a client can't send the id, an update makes every field optional. One class would have to loosen its fields until it fits every case.
Flashcard A PATCH sends only `price`. How do you avoid resetting the other fields?
Apply data.model_dump(exclude_unset=True): it keeps only the fields the client actually sent, so the others aren't overwritten with defaults.
Flashcard Why does Field(le=datetime.now().year) start rejecting valid books on a long-running server?
Field arguments are evaluated once, when the module is imported, so the year is frozen at startup. Check moving limits in a validator instead.