python data_error ai_generated true

pydantic_core._pydantic_core.ValidationError: 用户模型验证错误:name 字段缺失

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-validation-error-field-required

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

版本兼容性

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

根因分析

实例化 Pydantic 模型时输入数据缺少必填字段。在 Pydantic v2 中,缺失字段会抛出 ValidationError,而不是静默使用默认值。

English

A required field is missing from the input data when instantiating a Pydantic model. In Pydantic v2, missing fields raise ValidationError instead of silently defaulting.

generic

解决方案

  1. 95% 成功率
    from typing import Optional
    from pydantic import BaseModel
    
    class User(BaseModel):
        name: Optional[str] = None
        age: int
  2. 98% 成功率
    user = User(name='Alice', age=25)  # include all required fields
    # or
    User.model_validate({'name': 'Alice', 'age': 25})

无效尝试

常见但无效的做法:

  1. 85% 失败

    Silently swallowing ValidationError means downstream code receives an object with missing attributes, causing AttributeError later.

  2. 70% 失败

    Pydantic v2 models are immutable by default and reject attribute assignment unless model_config allows it.