python type_error ai_generated true

pydantic_core._pydantic_core.ValidationError: 1 validation error for User age 输入应为有效整数,无法将字符串解析为整数 [type=int_parsing, input_value='abc', input_type=str]

pydantic_core._pydantic_core.ValidationError: 1 validation error for User age Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='abc', input_type=str]

ID: python/pydantic-validation-error-model-type

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

版本兼容性

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

根因分析

Pydantic v2 默认严格模式下,将非数字字符串 'abc' 传入 int 字段时会因无法解析而抛出验证错误。

English

Pydantic v2 strict-by-default coercion fails when a string like 'abc' is passed to an int field; the type coercion cannot parse non-numeric strings.

generic

解决方案

  1. 92% 成功率
    from pydantic import BaseModel, field_validator
    class User(BaseModel):
        age: int
        @field_validator('age', mode='before')
        @classmethod
        def parse_age(cls, v):
            if isinstance(v, str) and not v.isdigit():
                raise ValueError('age must be numeric')
            return int(v)
  2. 95% 成功率
    from pydantic import ValidationError
    try:
        User(age='abc')
    except ValidationError as e:
        return {'errors': e.errors()}, 422

无效尝试

常见但无效的做法:

  1. 75% 失败

    strict=False still refuses to parse 'abc' into int because no valid numeric representation exists.

  2. 60% 失败

    This hides the error but downstream code expecting int will crash with TypeError.