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

I'm using SQLAlchemy ORM models alongside Pydantic models in a FastAPI context. Currently, I have:

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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信