【发布时间】: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