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
80%Fix Rate
88%Confidence
0Evidence
2024-04-22First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 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
-
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 -
85% success
UserOut(id=db_user.id, name=db_user.name)
Dead Ends
Common approaches that don't work:
-
60% fail
SQLAlchemy instances store state in _sa_instance_state; __dict__ includes internal keys and misses lazy relations.
-
70% fail
You're validating the class, not an instance; attributes are InstrumentedAttribute descriptors.
-
55% fail
In Pydantic v2 this raises a deprecation warning and is ignored unless from_attributes is set.