pydantic_core._pydantic_core.ValidationError: 1 个验证错误,字段 age 输入应为有效整数,无法将字符串解析为整数
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='twenty', input_type=str]
ID: python/pydantic-validation-error-input-type
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 2.x | active | — | — | — |
根因分析
Pydantic v2 严格类型转换:声明为 int 的字段收到了字符串,且该字符串不是数字字面量,因此 Pydantic 拒绝转换。与 v1 不同,v2 默认不再将任意字符串静默转换为整数。
English
Pydantic v2 strict type coercion: a string field was passed where an int was declared, and the string is not a numeric literal so Pydantic refuses to coerce it. Unlike v1, v2 no longer silently coerces arbitrary strings to ints by default.
解决方案
-
85% 成功率
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 v.isalpha(): words = {'twenty': 20, 'thirty': 30} return words.get(v.lower(), v) return v -
80% 成功率
from typing import Union from pydantic import BaseModel, BeforeValidator from typing_extensions import Annotated CoercedInt = Annotated[int, BeforeValidator(lambda v: int(v) if str(v).isdigit() else v)] class User(BaseModel): age: CoercedInt
无效尝试
常见但无效的做法:
-
90% 失败
Silently swallowing ValidationError means the invalid object never gets constructed; downstream code receives None or crashes with AttributeError later.
-
75% 失败
strict=False only relaxes some coercions; 'twenty' is not a valid integer representation and will still raise int_parsing.
-
60% 失败
v1 also raises for non-numeric strings like 'twenty'; the behavior difference is only for numeric-looking strings such as '25'.