python type_error ai_generated true

pydantic_core._pydantic_core.ValidationError: 1 validation error for Product price 输入应为有效的字符串 [type=string_type, input_value=19.99, input_type=float]

pydantic_core._pydantic_core.ValidationError: 1 validation error for Product price Input should be a valid string [type=string_type, input_value=19.99, input_type=float]

ID: python/pydantic-v2-string-type-coercion-strict

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

版本兼容性

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

根因分析

模型配置了 strict=True(或字段使用了 StrictStr),因此 Pydantic v2 拒绝将 float 强制转换为字符串,即使宽松模式会接受。

English

The model was configured with strict=True (or the field uses StrictStr), so Pydantic v2 refuses to coerce a float into a string even though lax mode would accept it.

generic

解决方案

  1. 93% 成功率
    Add a field_validator with mode='before' to coerce: `@field_validator('price', mode='before') @classmethod def coerce(cls, v): return str(v)`
  2. 90% 成功率
    Relax strictness per-field: `price: str = Field(strict=False)` while keeping the model strict.

无效尝试

常见但无效的做法:

  1. 60% 失败

    Pushes type-handling logic to every call site; easy to miss one and re-trigger the error

  2. 70% 失败

    Disables strictness everywhere, silently accepting bad data for unrelated fields