'Marshmallow How to Enforce a Required Field when Dumping?
>>> class Foo(Schema):
... id = fields.Int(dump_only=True, required=True)
... name = fields.Str(required=True)
...
>>>
>>> Foo().dump({'asdf': 'abc'})
{}
I would have thought that this would raise a ValidationError.
Is there anyway to get a Marshmallow schema to enforce the required fields when calling dump ?
Solution 1:[1]
Marshmallow only validates on load. It is a design choice.
You can use a pre_load method for this.
I just realized this could also be achieved with a default callable raising a ValidationError.
Untested code:
class Foo(Schema):
id = fields.Int(dump_only=True, required=True, default=lambda: raise ValidationError("missing id field")
name = fields.Str(required=True)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jérôme |
