python
data_error
ai_generated
true
pydantic_core._pydantic_core.ValidationError: User 校验失败 email 字段必填 [type=missing]
pydantic_core._pydantic_core.ValidationError: 1 validation error for User email Field required [type=missing, input_value={'name': 'Alice'}, input_type=dict]
ID: python/pydantic-validationerror-missing-field
80%修复率
88%置信度
0证据数
2024-03-12首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 2.x | active | — | — | — |
根因分析
模型中存在无默认值的必填字段,但传入构造函数的输入数据缺少该字段。
English
A required field without a default value is absent from the input payload passed to the model constructor.
解决方案
-
95% 成功率
class User(BaseModel): name: str email: str = "" # or use a default factory for mutable types from pydantic import Field class User(BaseModel): tags: list[str] = Field(default_factory=list) -
92% 成功率
from typing import Optional class User(BaseModel): email: Optional[str] = None -
88% 成功率
payload = {"name": "Alice"} payload.setdefault("email", "[email protected]") user = User(**payload)
无效尝试
常见但无效的做法:
-
85% 失败
Swallowing the exception leaves the object unconstructed or partially populated, causing AttributeError downstream and hiding the real data problem.
-
70% 失败
In Pydantic v2, Optional without a default is still required; validation still fails with the same missing error.
-
90% 失败
extra='allow' only permits additional keys; it does not supply values for missing required fields.