pydantic_core._pydantic_core.ValidationError:1 个验证错误(UserOut) id 输入应为有效的整数 [type=int_type, input_value=<sqlalchemy.orm.attributes.InstrumentedAttribute object>, input_type=InstrumentedAttribute]
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
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 2.x | active | — | — | — |
根因分析
将 SQLAlchemy 模型类(而非实例)传给 model_validate,或未启用 from_attributes,导致 Pydantic 读取的是类属性而非实例属性。
English
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.
解决方案
-
95% 成功率
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% 成功率
UserOut(id=db_user.id, name=db_user.name)
无效尝试
常见但无效的做法:
-
60% 失败
SQLAlchemy instances store state in _sa_instance_state; __dict__ includes internal keys and misses lazy relations.
-
70% 失败
You're validating the class, not an instance; attributes are InstrumentedAttribute descriptors.
-
55% 失败
In Pydantic v2 this raises a deprecation warning and is ignored unless from_attributes is set.