如何让Pydantic接受整数作为字符串类型参数并自动转换?
解决Pydantic v2中整数自动转为字符串参数的兼容问题
在Pydantic v2版本中,默认取消了早期版本里自动将整数转为字符串类型参数的行为,要实现参数兼容,可采用以下几种方案:
方案一:用BeforeValidator预处理输入
通过Annotated结合BeforeValidator,在验证阶段前将非字符串类型的输入转换为字符串:
from pydantic import BaseModel, BeforeValidator from typing import Annotated def convert_to_str(v): return str(v) if not isinstance(v, str) else v class FooBar(BaseModel): whatever: Annotated[str, BeforeValidator(convert_to_str)] # 测试可正常运行 FooBar(whatever=12) # 输出结果: FooBar(whatever='12')
方案二:自定义字符串字段类型
创建继承自str的自定义类型,重写核心验证逻辑实现自动转换:
from pydantic import BaseModel, GetCoreSchemaHandler from pydantic_core import core_schema class AutoStr(str): @classmethod def __get_pydantic_core_schema__(cls, source_type, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema: return core_schema.no_info_wrap_validator_function( cls.validate, core_schema.str_schema(), ) @classmethod def validate(cls, v): return str(v) if not isinstance(v, str) else v class FooBar(BaseModel): whatever: AutoStr # 测试可正常运行 FooBar(whatever=12) # 输出结果: FooBar(whatever='12')
方案三:Union类型配合模型配置(简易版)
如果仅需兼容整数与字符串,可直接使用Union[str, int],并通过模型配置coerce_numbers_to_str(v2.4及以上版本支持)实现自动转换:
from pydantic import BaseModel from typing import Union class FooBar(BaseModel): whatever: Union[str, int] model_config = {"coerce_numbers_to_str": True} # 测试可正常运行 FooBar(whatever=12) # 输出结果: FooBar(whatever='12')
注意:
coerce_numbers_to_str配置会对模型中所有字符串类型字段生效,将传入的数字自动转为字符串,适合全局需要该兼容逻辑的场景。
内容的提问来源于stack exchange,提问作者Joost Dübken
相关产品推荐
相关产品推荐

