作为外键引用的临时模型实例

Temporary model instances referenced as foreign keys

有没有办法将外键引用的 Django 模型实例保存在内存中而不将其存储到数据库中?

该代码是 _add_ 重载的一部分,但它现在的实现方式非常丑陋,因为很难跟踪新实例,而且它还会产生很多不必要的数据库访问。 理想情况下,只要用户不对返回的实例调用 save() 方法,我就希望临时保留新实例。

当我取消注释如下所示的 save() 调用时,返回的 Sequence 实例中未引用 SequenceAnnotation 实例。

    def __add__(self, other: Union['Sequence', str]):
        """
        This enables you to use the + operator when dealing with Sequence objects
        :param other:
        :return:
        """
        sum_seq = Sequence()

        # concatenate the actual sequences
        sum_seq.sequence = self.sequence + other.sequence

        #sum_seq.save()
        len_self_seq = len(self.sequence)

        # annotations
        annot: SequenceAnnotation
        # copy the own anntotations
        for annot in self.annotations.all():
            new_annot = deepcopy(annot)
            new_annot.id = None  # this is crucial to actually create a new instance
            new_annot.ref_sequence = sum_seq
            #new_annot.save()


        # copy the other annotations, adjust the start and end positions
        for annot in other.annotations.all():
            new_annot = deepcopy(annot)
            new_annot.id = None  # this is crucial to actually create a new instance
            new_annot.start = len_self_seq + annot.start
            new_annot.end = len_self_seq + annot.end
            new_annot.ref_sequence = sum_seq
            #new_annot.save()

        return sum_seq

没有,据我所知

Django 外键字段由 something_id 个字段支持;将 foo.something 分配给具有 None id sets the backing field to None.

的内容

您需要实施类似于表单(可能)save_m2m() 的方式,以确保对象群以正确的顺序保存。