Reputation: 6460
I have a simple problem and am unsure the best way to handle it. I have a schema defined as follows:
class MySchema(Schema):
title = fields.String(required=True)
imageUrl = fields.Url()
imageUrl
is an optional field, sometimes it will be None/null. If this happens, it's ok and it doesn't need to be a valid url. But I when I do:
my_schema.load(request.get_json())
on incoming data that is PUT, the url field records an error: Field may not be null.
I thought using partial=True
in the call to load would work, but it doesn't. I also didn't like that because this isn't a partial, it's the full object, it just so happens some of my fields are nullable in the DB.
How do I get marshmallow to validate the imageUrl when it is non-null, but to ignore it when it is null?
Upvotes: 18
Views: 23296
Reputation: 6460
I figured this out now. cdonts answer was close, but wasn't working for me. I did a careful re-read of the docs. default
is used to provide a default value for missing values during serialization.
However I was running in to the issue during deserialization and validation time. There are parameters for that too.
A combination of allow_none
and missing
was useful in my situation and solved my problem.
Copy from the doc (v3.20.1):
allow_none – Set this to True if None should be considered a valid value during validation/deserialization. If load_default=None and allow_none is unset, will default to True. Otherwise, the default is False.
https://marshmallow.readthedocs.io/en/stable/marshmallow.fields.html#marshmallow.fields.Field
The missing option is deprecated since 3.13.0 (2021-07-21): https://marshmallow.readthedocs.io/en/stable/changelog.html#id11.
Upvotes: 32
Reputation: 51
I upvoted the answer from @lostdorje since it is the correct one, a code example would be something like:
class MySchema(Schema):
field_1 = fields.Str(allow_none=True)
Upvotes: 5
Reputation: 9599
I think you should provide a default value.
class MySchema(Schema):
title = fields.String(required=True)
imageUrl = fields.Url(default=None)
Hope it helps!
Upvotes: 2