I'm using SQLAlchemy ORM models alongside Pydantic models in a FastAPI context. Currently, I have:
class CustomerModel(Base):
__tablename__ = "customers"
id: Mapped[UUID] = mapped_column(
primary_key=True, server_default=func.gen_random_uuid()
)
orders: Mapped[list[OrderModel]] = relationship(
back_populates="customer", cascade="all, delete-orphan", passive_deletes=True
)
name: Mapped[str | None]
Pydantic model:
class Customer(BaseModel):
orders: list[Order]
name: str
model_config = ConfigDict(from_attributes=True)
Usage:
db_customer: CustomerModel = get_customer_from_db(some_id)
return Customer.model_validate(db_customer)
I want to add a fallback for when the name is not known:
@model_validator(mode="wrap")
@classmethod
def parse(
cls, customer: t.Any, handler: ModelWrapValidatorHandler[t.Self]
) -> t.Self:
if not customer.name:
customer.name = generate_fallback_name(customer)
return handler(customer)
The problem is that the validator mutates the SQLAlchemy model instance directly, causing unintended persistence in the database. Detaching the model (using session.expunge()) also isn't ideal due to linked orders needing lazy loading.
Is there a common pattern for using validators in combination with ORM models?
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744200916a4562873.html
评论列表(0条)