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的设置没有关系。
两种解决方式
- 允许
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}
- 要求
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
相关产品推荐
相关产品推荐

