最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

sqlalchemy - How to use validators in pydantic for default values in combination with ORM mode? - Stack Overflow

programmeradmin4浏览0评论

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?

发布评论

评论列表(0)

  1. 暂无评论