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

- **ID:** `python/pydantic-type-error-int-parsing-string`
- **领域:** python
- **类别:** type_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

Pydantic v2 更严格的解析会拒绝非数字字符串赋给 `int` 字段，而 v1 会静默转换或抛出不同消息。

## 版本兼容性

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

## 解决方案

1. **** (90% 成功率)
   ```
   Use a custom validator: `@field_validator('age', mode='before')
@classmethod
def parse_age(cls, v):
    return int(v) if str(v).isdigit() else 0`
   ```
2. **** (88% 成功率)
   ```
   Change the field type to `Union[int, str]` and validate downstream, or use `Annotated[int, BeforeValidator(lambda v: int(v) if str(v).isdigit() else 0)]`.
   ```

## 无效尝试

- **** — Wrapping in `try/except ValueError` does not catch `ValidationError` in v2 because it is a separate exception type. (75% 失败率)
- **** — Using `int(value)` before passing to the model defeats the purpose and still raises for non-numeric input. (60% 失败率)
