Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

handling optional field validation

Tags:

marshmallow

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?

like image 599
lostdorje Avatar asked Jan 09 '16 06:01

lostdorje


2 Answers

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.

like image 50
lostdorje Avatar answered Oct 09 '22 23:10

lostdorje


I think you should provide a default value.

class MySchema(Schema):
    title = fields.String(required=True)
    imageUrl = fields.Url(default=None)

Hope it helps!

like image 20
cdonts Avatar answered Oct 10 '22 01:10

cdonts