python type_error ai_generated true

pydantic_core._pydantic_core.ValidationError: 产品模型验证错误:price 字段无法将字符串解析为整数

pydantic_core._pydantic_core.ValidationError: 1 validation error for Product price Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='19.99', input_type=str]

ID: python/pydantic-validation-error-int-parsing

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

版本兼容性

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

根因分析

向 int 类型字段传入了包含小数或非数字字符的字符串。Pydantic v2 严格解析会拒绝 '19.99' 这类字符串赋值给 int 字段。

English

A string value containing a decimal or non-numeric characters was passed to an int-typed field. Pydantic v2 strict parsing rejects strings like '19.99' for int fields.

generic

解决方案

  1. 95% 成功率
    from decimal import Decimal
    from pydantic import BaseModel
    
    class Product(BaseModel):
        price: Decimal
  2. 90% 成功率
    from pydantic import BaseModel, field_validator
    
    class Product(BaseModel):
        price: int
    
        @field_validator('price', mode='before')
        @classmethod
        def parse_price(cls, v):
            return int(float(v))

无效尝试

常见但无效的做法:

  1. 90% 失败

    int('19.99') raises ValueError because Python cannot directly cast a decimal string to int.

  2. 60% 失败

    Loses numeric semantics; downstream arithmetic operations will fail with TypeError.