Merge pull request #3431 from paolopaolopaolo/issue-3265

Guard against calling `serializer.data` before `serializer.save()`
This commit is contained in:
Tom Christie 2015-09-23 09:51:54 +01:00
commit 51443166a8
2 changed files with 16 additions and 0 deletions

View File

@ -166,6 +166,12 @@ class BaseSerializer(Field):
"For example: 'serializer.save(owner=request.user)'.'" "For example: 'serializer.save(owner=request.user)'.'"
) )
assert not hasattr(self, '_data'), (
"You cannot call `.save()` after accessing `serializer.data`."
"If you need to access data before committing to the database then "
"inspect 'serializer.validated_data' instead. "
)
validated_data = dict( validated_data = dict(
list(self.validated_data.items()) + list(self.validated_data.items()) +
list(kwargs.items()) list(kwargs.items())

View File

@ -51,6 +51,16 @@ class TestSerializer:
with pytest.raises(AttributeError): with pytest.raises(AttributeError):
serializer.data serializer.data
def test_data_access_before_save_raises_error(self):
def create(validated_data):
return validated_data
serializer = self.Serializer(data={'char': 'abc', 'integer': 123})
serializer.create = create
assert serializer.is_valid()
assert serializer.data == {'char': 'abc', 'integer': 123}
with pytest.raises(AssertionError):
serializer.save()
class TestValidateMethod: class TestValidateMethod:
def test_non_field_error_validate_method(self): def test_non_field_error_validate_method(self):