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)...並且它幾乎可行! (新的related_operation被添加到數據庫中,但是在保存後它會循環,它永遠不會結束,我不知道它在做什麼,我必須重新啓動apache才能從服務器獲得任何答案,也許這是愚蠢的錯誤或者非常複雜的東西 - 即時堆疊...
(當然操作類有多個字段如related_account,所以如果instance.related_account不無:是正確的)
UPDATE:
我發現問題在這裏:
def __init__(self, *args, **kwargs):
super(Operation, self).__init__(*args, **kwargs)
#self.__related_operation = self.related_operation
如果我註釋掉上面的一行 - 一切都會好的 - 但當然這是錯誤的 - 爲什麼它會阻止某事。
在模型的__init __(),交換兩行: 自.__ related_operation = self.related_operation 超(操作,個體經營).__的init __(* ARGS,** kwargs) – karthikr
有什麼區別嗎? (它不會改變任何東西 - 仍然hungs) –