确定模型已被删除

时间:2015-03-18 16:48:37

标签: django django-models

我想从我的模型delete方法中调用一个方法。是否有任何内置方法从该方法中知道当前是否正在删除模型,以便我不调用save并重新创建模型?在此示例中,我将如何编写$deleting

class MyModel(models.Model):
    def cleanup_stuff(self):
        do_something(self)
            self.xxx = None
            if not $deleting:
                self.save()

    def delete(self, *args, **kwargs):
        with transaction.atomic():
            super(MyModel, self).delete(*args, **kwargs)
            self.cleanup_stuff()

2 个答案:

答案 0 :(得分:1)

没有内置方式,但您可以在delete方法中轻松地在模型上设置自己的属性并检查其存在:

def delete(self, *args, **kwargs):
    self.is_being_deleted = True
    ...

def cleanup_stuff(self):
    if not getattr(self, 'is_being_deleted', False):
        self.save()
    ...

答案 1 :(得分:0)

据我所知,没有内置助手。我会在cleanup_stuff方法中使用和关键字参数:

def cleanup_stuff(self, deleting=False):
    ...

def delete(self, *args, **kwargs):
    with transaction.atomic():
        super(MyModel, self).delete(*args, **kwargs)
        self.cleanup_stuff(deleting=True)