You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pydantic自定义数据类型验证时无法获取值问题排查

问题原因

你的自定义数据类型的validate方法没有返回验证通过的值,Pydantic的验证器要求必须返回处理后的合法值,否则会默认将字段设为None。

修复方案

修改SelectionList类的validate方法,在验证通过后返回输入值:

class SelectionList(ABC):
    class_selection_list = []
    datatype = None

    @classmethod
    def __get_validators__(cls):
        yield cls.validate

    @classmethod
    def __modify_schema__(cls, field_schema):
        field_schema.update(selection_list=cls.class_selection_list, type=cls.datatype)

    @classmethod
    def validate(cls, v):
        if v not in cls.class_selection_list:
            raise Exception(f"Value must be one of this list: {str(cls.class_selection_list)}")
        # 新增:返回验证通过的值
        return v


class StatusType(str, SelectionList):
    class_selection_list = ["Active", "Inactive"]
    datatype = "string"
额外优化建议

因为StatusType继承了str,可以在返回时确保类型严格匹配(显式用子类实例化更符合类型设计逻辑):

@classmethod
def validate(cls, v):
    if v not in cls.class_selection_list:
        raise Exception(f"Value must be one of this list: {str(cls.class_selection_list)}")
    return cls(v)  # 用当前子类(StatusType)实例化后返回,满足str子类的类型要求

修改后,使用MyModel(**record)验证合法记录时,STATUS字段会正确赋值为传入的"Active"或"Inactive",不会再出现None的情况。

内容的提问来源于stack exchange,提问作者HuLu ViCa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 05:08:18