python config_error ai_generated true

pydantic.errors.PydanticUserError: `model_config` 不能用作模型字段名。请使用 `model_config` 作为模型配置。

pydantic.errors.PydanticUserError: `model_config` cannot be used as a model field name. Use `model_config` for model configuration.

ID: python/pydantic-config-error-json-schema-extra

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

版本兼容性

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

根因分析

v2 模型中定义了名为 `model_config` 的属性(通常从 v1 代码移植而来),而 Pydantic 保留该名称用于配置。

English

A v2 model defines an attribute literally named `model_config` (often ported from v1 code where the field was user-defined), which Pydantic reserves for configuration.

generic

解决方案

  1. 95% 成功率
    Rename the field and add an alias: `class M(BaseModel):
        model_config = ConfigDict(populate_by_name=True)
        cfg: dict = Field(alias='model_config')`
  2. 90% 成功率
    Use `Field(alias='model_config')` and read via `obj.cfg`; update all callers to use the new attribute name.

无效尝试

常见但无效的做法:

  1. 60% 失败

    Renaming only in the class but not in callers leaves `AttributeError` at runtime when code reads `obj.model_config`.

  2. 90% 失败

    Adding `class Config` alongside `model_config` triggers a second PydanticUserError about mixing v1 and v2 config styles.