python
type_error
ai_generated
true
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
80%Fix Rate
86%Confidence
0Evidence
2024-05-02First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 2.x | active | — | — | — |
Root Cause
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中文
模型配置了 strict=True(或字段使用了 StrictStr),因此 Pydantic v2 拒绝将 float 强制转换为字符串,即使宽松模式会接受。
Workarounds
-
93% success
Add a field_validator with mode='before' to coerce: `@field_validator('price', mode='before') @classmethod def coerce(cls, v): return str(v)` -
90% success
Relax strictness per-field: `price: str = Field(strict=False)` while keeping the model strict.
Dead Ends
Common approaches that don't work:
-
60% fail
Pushes type-handling logic to every call site; easy to miss one and re-trigger the error
-
70% fail
Disables strictness everywhere, silently accepting bad data for unrelated fields