python data_error ai_generated true

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

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 without a default value is absent from the input payload passed to the model constructor.

generic

中文

模型中存在无默认值的必填字段,但传入构造函数的输入数据缺少该字段。

Workarounds

  1. 95% success
    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)
  2. 92% success
    from typing import Optional
    class User(BaseModel):
        email: Optional[str] = None
  3. 88% success
    payload = {"name": "Alice"}
    payload.setdefault("email", "[email protected]")
    user = User(**payload)

Dead Ends

Common approaches that don't work:

  1. 85% fail

    Swallowing the exception leaves the object unconstructed or partially populated, causing AttributeError downstream and hiding the real data problem.

  2. 70% fail

    In Pydantic v2, Optional without a default is still required; validation still fails with the same missing error.

  3. 90% fail

    extra='allow' only permits additional keys; it does not supply values for missing required fields.