python config_error ai_generated true

pydantic.errors.PydanticUserError: 字段名 'model_config' 与父类 'BaseModel' 中的属性冲突

pydantic.errors.PydanticUserError: Field name 'model_config' shadows an attribute in parent 'BaseModel'

ID: python/pydantic-model-field-name-shadowing

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

版本兼容性

版本状态引入弃用备注
2.x active — — —

根因分析

自定义字段名与 BaseModel 的保留属性(如 model_config、model_fields、model_dump)冲突。

English

A user-defined field name collides with a reserved BaseModel attribute such as model_config, model_fields, or model_dump.

generic

解决方案

  1. 95% 成功率
    from pydantic import BaseModel, Field
    class Settings(BaseModel):
        config: dict = Field(alias="model_config")
  2. 90% 成功率
    class Settings(BaseModel):
        app_config: dict = Field(serialization_alias="model_config")

无效尝试

常见但无效的做法:

  1. 95% 失败

    BaseModel is from the Pydantic library; you cannot rename its attributes without forking.

  2. 80% 失败

    protected_namespaces controls the model_ prefix warning, not reserved attribute collisions.

  3. 70% 失败

    The Python attribute name still shadows the parent, so the error persists at class creation.