[Python] How to use validators in pydantic for default values in combination with ORM mode?

Discussão em 'Python' iniciado por Stack, Abril 14, 2025.

  1. Stack

    Stack Membro Participativo

    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?

    Continue reading...

Compartilhe esta Página