def save(self, **kwargs):
ismodel = isinstance(self, ApimasModelSerializer)
assert not hasattr(self, 'save_object'), (
'Serializer `%s.%s` has old-style version 2 `.save_object()` '
'that is no longer compatible with REST framework 3. '
'Use the new-style `.create()` and `.update()` methods instead.' %
(self.__class__.__module__, self.__class__.__name__)
)
assert hasattr(self, '_errors'), (
'You must call `.is_valid()` before calling `.save()`.'
)
assert not self.errors, (
'You cannot call `.save()` on a serializer with invalid data.'
)
# Guard against incorrect use of `serializer.save(commit=False)`
assert 'commit' not in kwargs, (
"'commit' is not a valid keyword argument to the 'save()' method. "
"If you need to access data before committing to the database then "
"inspect 'serializer.validated_data' instead. "
"You can also pass additional keyword arguments to 'save()' if you "
"need to set extra attributes on the saved model instance. "
"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. "
)
if ismodel:
validated_data = dict(
list(self.validated_data.items()) +
list(kwargs.items())
)
else:
validated_data = self.validated_data
if self.instance is not None:
self.instance = self.update(self.instance, validated_data)\
if ismodel else self.update(self.instance, validated_data,
**kwargs)
if ismodel:
assert self.instance is not None, (
'`update()` did not return an object instance.'
)
else:
self.instance = self.create(validated_data) if ismodel\
else self.create(validated_data, **kwargs)
if ismodel:
assert self.instance is not None, (
'`create()` did not return an object instance.'
)
return self.instance
评论列表
文章目录