I would like to call a method from my Model's delete
method. Is there any built-in way from within that method to know if the model is currently being deleted so that I do not call save
and recreate the model? In this example, how would I write $deleting
?
我想从我的Model的delete方法中调用一个方法。是否有任何内置方法从该方法中知道当前是否正在删除模型,以便我不调用save并重新创建模型?在这个例子中,我如何写$ delete?
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 个解决方案
#1
1
There's no built-in way, but you could easily set your own attribute on the model in the delete method and check for its existence:
没有内置方法,但您可以在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()
...
#2
0
As far as I know, there is no built-in helper. I would use and keyword argument in cleanup_stuff
method:
据我所知,没有内置助手。我会在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)
#1
1
There's no built-in way, but you could easily set your own attribute on the model in the delete method and check for its existence:
没有内置方法,但您可以在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()
...
#2
0
As far as I know, there is no built-in helper. I would use and keyword argument in cleanup_stuff
method:
据我所知,没有内置助手。我会在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)