Allow load to add missing fields with default values
See original GitHub issueWhen I have something like this:
from marshmallow import Schema, fields
class UserSchema(Schema):
name = fields.Str(required=True)
email = fields.Email(required=True)
created_at = fields.DateTime()
some_other = fields.Str(default='This is something else')
user_data = {
'created_at': '2014-08-11T05:26:03.869245',
'email': u'ken@yahoo.com',
'name': u'Ken'
}
schema = UserSchema()
result = schema.load(user_data)
pprint(result)
I currently get:
{'created_at': datetime.datetime(2014, 8, 11, 5, 26, 3, 869245),
'email': 'ken@yahoo.com',
'name': 'Ken'}
I would expect that some_other
would be added with the default set to This is something else
, especially if we are passing this to @post_load
to create an object so that I don’t have to have said object also handle setting the default (and potentially getting out of sync).
This is especially handy when using marshmallow to validate and transform the data as necessary on a load before passing it further down the stack to avoid having to add a bunch of if key in obj
statements.
Currently I end up doing:
result = schema.dump(schema.load(user_data))
pprint(result)
Which does have the desired result:
{'created_at': '2014-08-11T05:26:03.869245+00:00',
'email': 'ken@yahoo.com',
'name': 'Ken',
'some_other': 'This is something else'}
but is doing a lot of extra work that shouldn’t be necessary.
Is there already a recipe for doing something like this with a @post_load
decorator? If so I don’t mind using that.
Issue Analytics
- State:
- Created 5 years ago
- Reactions:2
- Comments:7 (2 by maintainers)
Top GitHub Comments
It does seem arbitrary for
default
to only be used for serialization. It isn’t immediately obvious thatmissing
is the deserialization complement. It would be nice if there was a little more symmetry here. Maybe something likedefault_load
,default_dump
, anddefault
to set both at once.If only I had the nagging feeling to check the docs for
Field
before I opened this issue and foundmissing
.Sorry for the noise!