python
config_error
ai_generated
true
pydantic_core._pydantic_core.ValidationError:1 个验证错误(User) userName 字段必填 [type=missing, input_value={'user_name': 'a'}, input_type=dict]
pydantic_core._pydantic_core.ValidationError: 1 validation error for User userName Field required [type=missing, input_value={'user_name': 'a'}, input_type=dict]
ID: python/pydantic-alias-population
80%修复率
88%置信度
0证据数
2024-03-30首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 2.x | active | — | — | — |
根因分析
字段声明了 alias='userName',但输入字典使用 Python 名 'user_name'。未启用 populate_by_name。
English
Field declared with alias='userName' but input dict uses the Python name 'user_name'. populate_by_name was not enabled.
解决方案
-
95% 成功率
from pydantic import BaseModel, Field, ConfigDict class User(BaseModel): model_config = ConfigDict(populate_by_name=True) user_name: str = Field(alias='userName') -
90% 成功率
from pydantic import BaseModel, Field, AliasChoices class User(BaseModel): user_name: str = Field(validation_alias=AliasChoices('userName', 'user_name'))
无效尝试
常见但无效的做法:
-
50% 失败
Violates PEP 8 and breaks all Python call sites using user_name.
-
65% 失败
Pydantic raises a name conflict error at class definition time.
-
55% 失败
Every caller must know the alias; error-prone and hides schema drift.