python type_error ai_generated true

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

其他格式: JSON · Markdown 中文 · English
80%修复率
88%置信度
0证据数
2024-04-22首次发现

版本兼容性

版本状态引入弃用备注
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.

generic

解决方案

  1. 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
  2. 85% 成功率
    UserOut(id=db_user.id, name=db_user.name)

无效尝试

常见但无效的做法:

  1. 60% 失败

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

  2. 70% 失败

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

  3. 55% 失败

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