django删除模型并覆盖删除方法

时间:2010-04-30 19:30:31

标签: django django-models

我有2个模特

class Vhost(models.Model):
    dns = models.ForeignKey(DNS)
    user = models.ForeignKey(User)
    extra = models.TextField()


class ApplicationInstalled(models.Model):
    user = models.ForeignKey(User)
    added = models.DateTimeField(auto_now_add=True)
    app = models.ForeignKey(Application)
    ver = models.ForeignKey(ApplicationVersion)
    vhost = models.ForeignKey(Vhost)
    path = models.CharField(max_length=100, default="/")


    def delete(self):

        #
        # remove the files
        #
        print "need to remove some files"


        super(ApplicationInstalled, self).delete()

如果我执行以下操作

>>> vhost = Vhost.objects.get(id=10)
>>> vhost.id
10L
>>> ApplicationInstalled.objects.filter(vhost=vhost)
[<ApplicationInstalled: http://wiki.jy.com/>]
>>> vhost.delete()
>>> ApplicationInstalled.objects.filter(vhost=vhost)
[]

正如您所看到的,有一个应用程序安装的对象链接到vhost但是当我删除vhost时,应用程序安装的对象已经消失,但打印永远不会被调用。

任何简单的方法都可以在不重复vhost删除对象的情况下执行此操作吗?

解决方案

def delete_apps(sender, **kwargs):
    obj = kwargs['instance']

    print "need to delete apps"


pre_delete.connect(delete_apps, sender=ApplicationInstalled)

1 个答案:

答案 0 :(得分:5)

自从django得到signals以来,我发现我几乎不需要覆盖保存/删除。

无论您需要做什么,都可以通过pre_deletepost_delete信号完成。

在这种情况下,您似乎想要在pre_delte信号中delete in bulk