mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-08-08 14:24:48 +03:00
Fixed #3265:
- '_called_data_property' flag added to BaseSerializer - '_called_data_property' is False until serializer.data is called, at which point it becomes True - Assert statement added to '.save()', will throw AssertionError if '_called_data_property' is True
This commit is contained in:
parent
f2c65512c6
commit
72cd350944
|
@ -79,6 +79,7 @@ class BaseSerializer(Field):
|
|||
.errors - Not available.
|
||||
.data - Available.
|
||||
"""
|
||||
_called_data_property = False
|
||||
|
||||
def __init__(self, instance=None, data=empty, **kwargs):
|
||||
self.instance = instance
|
||||
|
@ -166,6 +167,13 @@ class BaseSerializer(Field):
|
|||
"For example: 'serializer.save(owner=request.user)'.'"
|
||||
)
|
||||
|
||||
# Guard against calling 'serializer.data' before calling 'serializer.save()'
|
||||
assert not self._called_data_property, (
|
||||
"You should not access `.data` property before calling `.save()`."
|
||||
"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())
|
||||
|
@ -230,6 +238,8 @@ class BaseSerializer(Field):
|
|||
self._data = self.to_representation(self.validated_data)
|
||||
else:
|
||||
self._data = self.get_initial()
|
||||
|
||||
self._called_data_property = True
|
||||
return self._data
|
||||
|
||||
@property
|
||||
|
|
Loading…
Reference in New Issue
Block a user