marshmallow

handling optional field validation


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?


Solution

  • 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.