python data_error ai_generated true

pydantic_core._pydantic_core.ValidationError:1 个验证错误(Model) age 输入应为有效的整数,无法将字符串解析为整数 [type=int_parsing, input_value='twenty', input_type=str]

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

ID: python/pydantic-int-parsing-string

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

版本兼容性

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

根因分析

向 int 字段传入了诸如 'twenty' 或 '12.5' 的字符串。Pydantic v2 的严格解析拒绝强制转换非数字字符串。

English

A string like 'twenty' or '12.5' was passed to an int field. Pydantic v2 strict parsing refuses to coerce non-numeric strings.

generic

解决方案

  1. 90% 成功率
    from pydantic import BaseModel, field_validator
    class M(BaseModel):
        age: int
        @field_validator('age', mode='before')
        @classmethod
        def coerce(cls, v):
            if isinstance(v, str) and v.isdigit():
                return int(v)
            return v
  2. 85% 成功率
    from fastapi import FastAPI, HTTPException
    from pydantic import ValidationError
    try:
        M(**payload)
    except ValidationError as e:
        raise HTTPException(422, e.errors())

无效尝试

常见但无效的做法:

  1. 62% 失败

    int() raises ValueError inside validators, producing a confusing 500 rather than a clean ValidationError.

  2. 48% 失败

    strict=False still won't parse 'twenty' into an int; it only relaxes numeric-string coercion of digits.

  3. 35% 失败

    Loses field-level detail and downstream code relying on .errors() breaks.