python type_error ai_generated true

pydantic_core._pydantic_core.ValidationError: 1 validation error for UserOut id Input should be a valid integer [type=int_type, input_value=<sqlalchemy.orm.attributes.InstrumentedAttribute object>, input_type=InstrumentedAttribute]

ID: python/pydantic-orm-mode-from-attributes

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-04-22First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
2.x active

Root Cause

Passing a SQLAlchemy model class (not an instance) to model_validate, or from_attributes not enabled so Pydantic reads the class attribute instead of the instance.

generic

中文

将 SQLAlchemy 模型类(而非实例)传给 model_validate,或未启用 from_attributes,导致 Pydantic 读取的是类属性而非实例属性。

Workarounds

  1. 95% success
    from pydantic import BaseModel, ConfigDict
    class UserOut(BaseModel):
        model_config = ConfigDict(from_attributes=True)
        id: int
        name: str
    
    UserOut.model_validate(db_user)  # db_user is a SQLAlchemy instance
  2. 85% success
    UserOut(id=db_user.id, name=db_user.name)

Dead Ends

Common approaches that don't work:

  1. 60% fail

    SQLAlchemy instances store state in _sa_instance_state; __dict__ includes internal keys and misses lazy relations.

  2. 70% fail

    You're validating the class, not an instance; attributes are InstrumentedAttribute descriptors.

  3. 55% fail

    In Pydantic v2 this raises a deprecation warning and is ignored unless from_attributes is set.