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

Marshmallow Schema验证报错:allow_none=True仍致name字段验证失败

Marshmallow中allow_none=True仍触发验证失败的原因

你遇到的问题核心是混淆了required=True和allow_none=True的作用:

  • required=True的规则是字段必须出现在输入数据里,和字段值是什么无关
  • allow_none=True只是允许字段的值为None,但前提是这个字段本身要存在于输入数据中

你的输入{"age": None}里根本没有name字段,所以触发的是required=True的验证报错,和allow_none=True的设置没有关系。

两种解决方式

  1. 允许name字段不存在:去掉required=True,只保留allow_none=True,这样字段既可以不出现,出现时也允许值为None
class MySchema(Schema):
    name = fields.String(allow_none=True)
    age = fields.Integer(allow_none=True)

schema = MySchema()
data = {"age": None}
result = schema.load(data)
print(result)  # 输出: {'age': None}
  1. 要求name字段必须存在,但允许值为None:输入数据里必须明确包含name: None
class MySchema(Schema):
    name = fields.String(required=True, allow_none=True)
    age = fields.Integer(allow_none=True)

schema = MySchema()
data = {"name": None, "age": None}
result = schema.load(data)
print(result)  # 输出: {'name': None, 'age': None}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 13:34:56