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?
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.
I think you should provide a default value.
class MySchema(Schema):
title = fields.String(required=True)
imageUrl = fields.Url(default=None)
Hope it helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With