Default values should not be applied to partial updates

This commit is contained in:
Tom Christie 2016-08-02 12:47:57 +01:00
parent 5cbdfaed9e
commit b381c329fa
3 changed files with 7 additions and 4 deletions

View File

@ -49,7 +49,9 @@ Defaults to `False`
### `default`
If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behavior is to not populate the attribute at all.
If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behaviour is to not populate the attribute at all.
The `default` is not applied during partial update operations, in which case, only fields that are provided will have a validated value returned.
May be set to a function or other callable, in which case the value will be evaluated each time it is used. When called, it will receive no arguments. If the callable has a `set_context` method, that will be called each time before getting the value with the field instance as only argument. This works the same way as for [validators](validators.md#using-set_context).

View File

@ -435,7 +435,8 @@ class Field(object):
return `empty`, indicating that no value should be set in the
validated data for this field.
"""
if self.default is empty:
if self.default is empty or getattr(self.root, 'partial', False):
# No default, or this is a partial update.
raise SkipField()
if callable(self.default):
if hasattr(self.default, 'set_context'):

View File

@ -324,11 +324,11 @@ class TestDefaultInclusions:
assert serializer.validated_data == {'char': 'abc', 'integer': 456}
assert serializer.errors == {}
def test_default_should_not_be_included_on_update(self):
def test_default_should_be_included_on_update(self):
instance = MockObject(char='def', integer=123)
serializer = self.Serializer(instance, data={'integer': 456})
assert serializer.is_valid()
assert serializer.validated_data == {'integer': 456}
assert serializer.validated_data == {'char': 'abc', 'integer': 456}
assert serializer.errors == {}
def test_default_should_not_be_included_on_partial_update(self):