【问题标题】:Temporary model instances referenced as foreign keys作为外键引用的临时模型实例
【发布时间】:2022-01-10 10:52:13
【问题描述】:

有没有办法将 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

【问题讨论】:

    标签: python django django-models django-database


    【解决方案1】:

    没有,据我所知。

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

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

    【讨论】:

    • 嗨@AKX,我会再等一会儿,以防其他人有提议,但感谢您的回答。我很惊讶这个用例似乎没有简单的解决方案......我想象了一些奇迹代码,只要没有 ID,它可能会用某种指针替换丢失的外键,但它看起来像没那么容易……
    猜你喜欢
    • 2020-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-02
    • 1970-01-01
    • 2011-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多