python data_error ai_generated true

pydantic_core._pydantic_core.ValidationError: 1 validation error for User name 字段必填 [type=missing, input_value={'age': 25}, input_type=dict]

pydantic_core._pydantic_core.ValidationError: 1 validation error for User name Field required [type=missing, input_value={'age': 25}, input_type=dict]

ID: python/pydantic-v2-field-required-missing

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

版本兼容性

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

根因分析

输入数据中缺少了必填字段。在 Pydantic v2 中,没有默认值的字段是必填的,传入缺少该字段的字典会抛出 missing 类型的 ValidationError。

English

A required field was omitted from the input data. In Pydantic v2, fields without a default are mandatory, and passing a dict that lacks them raises a missing-field ValidationError.

generic

解决方案

  1. 95% 成功率
    Provide a default value: `name: str = ''` or `name: str = Field(default='unknown')`. Use `Optional[str] = None` if the field is genuinely optional.
  2. 88% 成功率
    Use model_validate with a pre-filled dict: `User.model_validate({'name': 'anon', **input_data})` so missing keys fall back to defaults.
  3. 70% 成功率
    Validate partial data with `User.model_construct(**input_data)` when you only need a best-effort object without validation.

无效尝试

常见但无效的做法:

  1. 75% 失败

    Hides the real data problem; downstream code receives an incomplete or default object and fails later with confusing AttributeError

  2. 90% 失败

    extra='allow' only affects unexpected fields, not missing required ones; the ValidationError persists