serializers.py 文件源码

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

项目:esdc-ce 作者: erigones 项目源码 文件源码
def restore_object(self, attrs, instance=None):
        """
        Restore the model instance.
        """
        m2m_data = {}
        related_data = {}
        nested_forward_relations = {}
        # noinspection PyProtectedMember
        meta = self.opts.model._meta

        # Reverse fk or one-to-one relations
        for (obj, model) in meta.get_all_related_objects_with_model():
            field_name = obj.get_accessor_name()
            if field_name in attrs:
                related_data[field_name] = attrs.pop(field_name)

        # Reverse m2m relations
        for (obj, model) in meta.get_all_related_m2m_objects_with_model():
            field_name = obj.get_accessor_name()
            if field_name in attrs:
                m2m_data[field_name] = attrs.pop(field_name)

        # Forward m2m relations
        if issubclass(meta.many_to_many.__class__, tuple):
            temp_m2m = list(meta.many_to_many)
        else:
            temp_m2m = meta.many_to_many
        for field in temp_m2m + meta.virtual_fields:
            if isinstance(field, GenericForeignKey):
                continue
            if field.name in attrs:
                m2m_data[field.name] = attrs.pop(field.name)

        # Nested forward relations - These need to be marked so we can save
        # them before saving the parent model instance.
        for field_name in attrs.keys():
            if isinstance(self.fields.get(field_name, None), Serializer):
                nested_forward_relations[field_name] = attrs[field_name]

        # Create an empty instance of the model
        if instance is None:
            instance = self.opts.model()

        for key, val in attrs.items():
            try:
                setattr(instance, key, val)
            except ValueError:
                self._errors[key] = [self.error_messages['required']]

        # Any relations that cannot be set until we've
        # saved the model get hidden away on these
        # private attributes, so we can deal with them
        # at the point of save.
        instance._related_data = related_data
        instance._m2m_data = m2m_data
        instance._nested_forward_relations = nested_forward_relations

        return instance
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号