mirror of
https://github.com/encode/django-rest-framework.git
synced 2024-11-27 03:54:01 +03:00
Merge pull request #3431 from paolopaolopaolo/issue-3265
Guard against calling `serializer.data` before `serializer.save()`
This commit is contained in:
commit
51443166a8
|
@ -166,6 +166,12 @@ class BaseSerializer(Field):
|
|||
"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(
|
||||
list(self.validated_data.items()) +
|
||||
list(kwargs.items())
|
||||
|
|
|
@ -51,6 +51,16 @@ class TestSerializer:
|
|||
with pytest.raises(AttributeError):
|
||||
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:
|
||||
def test_non_field_error_validate_method(self):
|
||||
|
|
Loading…
Reference in New Issue
Block a user