班上:
class Operation(models.Model):
related_operation = models.ForeignKey('self', null = True)
__related_operation = None
def __init__(self, *args, **kwargs):
super(Operation, self).__init__(*args, **kwargs)
self.__related_operation = self.related_operation
def save(self, force_insert=False, force_update=False):
if self.related_operation != self.__related_operation:
del self.__related_operation
super(Operation, self).save(force_insert, force_update)
self.__related_operation = self.related_operation
编码:
(...)
OperationFormSet = modelformset_factory(Operation, form=OperationCategoryOnlyForm)
if request.method == "POST":
formset = OperationFormSet(request.POST, queryset=Operation.objects.filter(category=category_id))
if formset.is_valid():
instances = formset.save(commit = False)
for instance in instances:
if instance.related_account is not None:
related_operation = Operation()
related_operation.related_operation = instance
related_operation.save()
instance.related_operation = related_operation
instance.save()
formset = OperationFormSet(queryset=Operation.objects.filter(category=category_id))
else:
formset = OperationFormSet(queryset=Operation.objects.filter(category=category_id))
和问题:
没有覆盖方法保存一切正常,但如果我改变了相关的操作形式,它当然会进行第二,第三等等相关的操作。
所以我决定覆盖保存方法 - 并添加 __related_operation。在保存期间,它会检查related_operation 是否发生了变化——如果是这样——它应该删除旧的related_operation 而不是保存(创建一个全新的related_operation)......它几乎可以工作了!(新的related_operation被添加到数据库,但它在保存后循环。它永远不会结束。我不知道它在做什么。我必须重新启动apache才能从服务器获得任何答案。也许这是愚蠢的错误输入或非常复杂的东西 -我堆积...
(当然操作类有多个字段如related_account,所以if instance.related_account is not None: 是正确的)
更新:
我发现,问题出在这里:
def __init__(self, *args, **kwargs):
super(Operation, self).__init__(*args, **kwargs)
#self.__related_operation = self.related_operation
如果我注释掉上面的那一行——一切正常——但当然是错的——为什么它会阻止某事。