This repository has been archived by the owner on Jan 28, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
missing vs default
Sergey Vilgelm edited this page Aug 15, 2018
·
1 revision
Marshmallow library has two different parameter of the field types are used for default value: missing and default.
- Missing is used for deserialization if the field is not found in the input data.
- Default is used for serialization if the input value is missing.
import marshmallow_objects as marshmallow
class MySchema(marshmallow.Schema):
field = marshmallow.fields.Str(default='field_default_value',
missing='field_missing_value')
print(MySchema().load({}))
print(MySchema().dump({}))
# {'field': 'field_missing_value'}
# {'field': 'field_default_value'}
The field
was not found in raw dat ({}
) and the value from missing
parameter was used at load
(deserialization) and the value from default
was used at dump
(serialization). It really works with a dictionary, but there is a totally different behavior with an object.
class MyObject(object):
def __init__(self, field=None):
self.field = field
def __repr__(self):
return '<MyObject(field={self.field!r})>'.format(self=self)
class MySchema(marshmallow.Schema):
field = marshmallow.fields.Str(default='field_default_value',
missing='field_missing_value')
@marshmallow.post_load
def make_object(self, data):
return MyObject(**data)
print(MySchema().load({}))
print(MySchema().dump(MyObject(**{})))
# <MyObject(field='field_missing_value')>
# {'field': None}
load
function works fine, there is no field
in the raw data ({}
) and the value from missing
parameter was used, but dump
function didn't used the value from default
parameter, because It found field
field in the object.
So with marshmallow-objects
models the missing
parameter should be used, not default
.
class MyModel(marshmallow.Model):
field = marshmallow.fields.Str(default='field_default_value',
missing='field_missing_value')
print(MyModel.load({}))
print(MyModel(**{}).dump())
# {'field': 'field_missing_value'}
# {'field': 'field_missing_value'}