# pydantic_core._pydantic_core.ValidationError: 1 个验证错误，字段 age 输入应为有效整数，无法将字符串解析为整数

- **ID:** `python/pydantic-validation-error-input-type`
- **领域:** python
- **类别:** data_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

Pydantic v2 严格类型转换：声明为 int 的字段收到了字符串，且该字符串不是数字字面量，因此 Pydantic 拒绝转换。与 v1 不同，v2 默认不再将任意字符串静默转换为整数。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 2.x | active | — | — |

## 解决方案

1. **** (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
   ```
2. **** (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
   ```

## 无效尝试

- **** — Silently swallowing ValidationError means the invalid object never gets constructed; downstream code receives None or crashes with AttributeError later. (90% 失败率)
- **** — strict=False only relaxes some coercions; 'twenty' is not a valid integer representation and will still raise int_parsing. (75% 失败率)
- **** — v1 also raises for non-numeric strings like 'twenty'; the behavior difference is only for numeric-looking strings such as '25'. (60% 失败率)
