serializers.py 文件源码

python
阅读 19 收藏 0 点赞 0 评论 0

项目:apimas 作者: grnet 项目源码 文件源码
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
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号