问题描述
我有一个问题,因为我正在使用some_widget_instance.delete()删除一个Widget。我还有一个名为WidgetFile的模型,带有一个覆盖delete()方法,以便当WidgetFile被删除时,我可以从我的硬盘驱动器上删除文件。我遇到的问题是,如果我删除一个Widget,并且它具有与此相关的WidgetFiles:
I'm having a problem because I'm deleting a Widget by using some_widget_instance.delete(). I also have a model called WidgetFile with an override delete() method so that I can delete files off my hard drive when a WidgetFile is deleted. The problem I'm having is that if I delete a Widget, and it has WidgetFiles related to it like this:
class WidgetFile(models.Model):
widget = models.ForeignKey(Widget)
嗯,当我删除这个Widget,它的WidgetFiles被删除,但是delete()方法不会触发并且做我额外的硬盘驱动器的东西。非常感谢任何帮助。
Well, when I delete that Widget, it's WidgetFiles are deleted but the delete() method doesn't trigger and do my extra hard drive stuff. Any help is much appreciated.
推荐答案
我想出来了。我只是把这个Widget的模型:
I figured it out. I just put this on that Widget model:
def delete(self):
files = WidgetFile.objects.filter(widget=self)
if files:
for file in files:
file.delete()
super(Widget, self).delete()
这触发了每个相关对象上必需的delete()方法,从而触发了我的自定义文件删除代码。数据库更昂贵是的,但是当您尝试在硬盘驱动器上删除文件时,再次点击数据库并不是一个很大的代价。
This triggered the necessary delete() method on each of the related objects, thus triggering my custom file deleting code. It's more database expensive yes, but when you're trying to delete files on a hard drive anyway, it's not such a big expense to hit the db a few extra times.
这篇关于如何覆盖模型上的delete(),并且仍然可以使用相关的删除操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!