python data_error ai_generated true

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-03-12First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
2.x active

Root Cause

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

中文

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

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 75% fail

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

  2. 90% fail

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