13

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?

Thomas Junk
  • 5,588
  • 2
  • 30
  • 43
lostdorje
  • 6,150
  • 9
  • 44
  • 86

3 Answers3

26

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.

lostdorje
  • 6,150
  • 9
  • 44
  • 86
  • 8
    It would help to show some code about how you used `allow_none` and `missing`, and to add a link to the related docs. – Luke Oct 24 '22 at 21:39
5

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)
JayD
  • 51
  • 1
  • 1
1

I think you should provide a default value.

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

Hope it helps!

cdonts
  • 9,304
  • 4
  • 46
  • 72
  • 1
    Thanks, but unfortunately that doesn't work. If a request comes in the imageUrl=None, the default has no effect and validation still fails. If a request comes in with the imageUrl missing completely, then there is no validation error, but the key is not added to the loaded request. – lostdorje Jan 10 '16 at 02:43
  • Your example is invalid. It doesn't work. – Ahmed Mar 16 '21 at 21:05