禁止使用save()防止由于未保存的相关对象“ xxxxxxxx”而导致数据丢失

时间:2019-07-09 12:14:35

标签: python django

我正在尝试在Django中创建逻辑,以在保存模型本身之前检查是否所有<项目都已保存。这是我正在使用的代码:

TabularInline

当条件 def save_formset(self, request, form, formset, change): instances = formset.save(commit=False) for instance in instances: item_count_in_origin = instance.prc_item.quantity print(item_count_in_origin) if instance.quantity > item_count_in_origin: messages.error(request, 'Quantity is higher than origin branch.') return else: for item in instances: if item.id is not None: item.close() else: formset.save() def save_model(self, request, obj, form, change): if obj.transfer_items.all().count() != 0: user = request.user if self.save_formset: if not change: obj.solicitor = user obj.date_solicited = datetime.now() created_status = Status.objects.get(name=StatusEnum.CREATED) obj.status = created_status return super(TransferenceAdmin, self).save_model(request, obj, form, change) else: messages.error(request, 'Quantity is higher than origin branch.') return 起作用时,它会正确运行并返回一个错误,但是当条件为假时,我们进入

if instance.quantity > item_count_in_origin:

它失败,并显示错误 for item in instances: if item.id is not None: item.close() else: formset.save()

更新

我将save() prohibited to prevent data loss due to unsaved related object 'xxxxxxxx'.更改为if item.id is not None:,以确保if item.id is None:仅在打开的实例上运行,而不在已保存的实例上运行。

错误变成item.close(),我认为这是关闭打开实例的错误方法。

0 个答案:

没有答案