In Django, you may encounter a problem when using the admin interface to bulk delete models - it does not trigger the
of the models when they are deleted in bulk. This is because the delete function in the admin interface calls
does not call your model's
delete() method (see the warning box on this
page of the documentation).
This can be undesirable when you have overridden the default
Model.delete() method to define some extra behaviour, for
example, cleaning up other models.
To remedy this, the Django documentation suggests writing a custom admin "action", however this does not help if models are deleted in bulk via foreign key relationships for example. A much better solution is to just not override the
and instead define your extra behaviour using the
These "signals" are triggered before and after a model is deleted respectively, regardless of how the model is deleted. So instead of something like this:
class MyModel(models.Model): ... def delete(self): print "deleting %s" % self ...
delete() method is overridden, simply get rid of the method and instead use this:
from django.db.models.signals import pre_delete from django.dispatch.dispatcher import receiver @receiver(pre_delete, sender=MyModel) def _mymodel_delete(sender, instance, **kwargs): print "deleting %s" % instance ...
It's that simple. Now admin bulk deletes and queryset deletes will still call this custom behaviour.