marshmallow icon indicating copy to clipboard operation
marshmallow copied to clipboard

String default not working correctly

Open juanrossi opened this issue 10 years ago • 1 comments

Hello, I'm not sure if this is a bug or an issue I'm having.

I'm trying to marshall some NULL fields as an empty string and other values using default but I always get None.

from marshmallow import Schema, fields

class TestSchema(Schema):
    position = fields.String(default='')


model = session.query(Model).get(1)
TestSchema().dump(model).data

Model has a property position that can be null (and is), but the default is never applied. I also tried using 'a' as default and missing, but I always get:

{u'position': None}

juanrossi avatar Jan 25 '16 14:01 juanrossi

default is only used used when for missing inputs to serialization.

TestSchema().dump({}).data['position']  # ''

None is not treated in a special way. Your model has a None attribute, so it is not missing. To illustrate:

TestSchema().dump({'position': None}).data['position']  # None

You could use a post_dump method to covert Nones to empty strings.

sloria avatar Jan 31 '16 14:01 sloria