Pydantic interop¶
dorm.contrib.pydantic.DormSchema
¶
Bases: BaseModel
Pydantic BaseModel with two ergonomic boosts:
from_attributes=Trueis on by default, so FastAPI can serialize a dorm instance directly viaresponse_model=YourSchema.- Subclasses can declare
class Meta: model = SomeDormModel(with optionalfields,exclude,optionallists) and the metaclass auto-fills the matching Pydantic fields. Anything you declare explicitly on the class wins over the Meta-derived defaults.
Without a Meta block, DormSchema is just a plain BaseModel
with the from_attributes config — useful when you want a fully
explicit, type-safe schema.
Example::
from pydantic import field_validator
from dorm.contrib.pydantic import DormSchema
class UserOut(DormSchema):
class Meta:
model = User
fields = "__all__" # default; or list to whitelist
class UserCreate(DormSchema):
confirm_password: str # extra field
@field_validator("email")
@classmethod
def lower(cls, v: str) -> str:
return v.lower()
class Meta:
model = User
exclude = ("id", "created_at")
optional = ("phone",) # nullable in this schema only
Nested relations: pass Meta.nested mapping a relation field name
to the sub-schema you want serialized. FK / O2O become the sub-schema
(Type | None if nullable); M2M becomes list[SubSchema]::
class PublisherOut(DormSchema):
class Meta:
model = Publisher
class AuthorOut(DormSchema):
class Meta:
model = Author
nested = {"publisher": PublisherOut} # author.publisher → PublisherOut | None
dorm.contrib.pydantic.schema_for(model_cls: Type[Model], *, name: str | None = None, exclude: tuple[str, ...] = (), only: tuple[str, ...] | None = None, optional: tuple[str, ...] = (), base: Type[BaseModel] = BaseModel) -> Type[BaseModel]
¶
Generate a Pydantic v2 BaseModel mirroring model_cls.
The result has model_config = ConfigDict(from_attributes=True) so
Pydantic can read values directly from dorm instances — i.e. you can
pass a dorm model to Schema.model_validate(instance) or use it as
a FastAPI response_model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_cls
|
Type[Model]
|
The dorm Model class. |
required |
name
|
str | None
|
Class name for the generated Pydantic model. Defaults to
|
None
|
exclude
|
tuple[str, ...]
|
Field names to omit. Common for input schemas (e.g.
|
()
|
only
|
tuple[str, ...] | None
|
If given, include only these field names. |
None
|
optional
|
tuple[str, ...]
|
Field names that should be Optional with a default of
|
()
|
base
|
Type[BaseModel]
|
Custom |
BaseModel
|
ManyToManyField is always excluded (M2M lives in a junction table; the
pks aren't on the row itself). Add an explicit tags: list[int] = []
in a wrapper schema if you need to model them.