In Django, you may encounter a problem when using the admin interface to bulk delete models - it does not trigger the delete()
method of the models when they are deleted in bulk. This is because the delete function in the admin interface calls QuerySet.delete()
which does not call your model'sdelete()
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 Model.delete()
, and instead define your extra behaviour using thepre_delete
or post_delete
model signals.
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
...
where the 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.
原地址:http://www.maxjaderberg.com/blog/0005/django-admin-multiple-delete/
The delete select action uses the queryset's delete method [1], which
means the model's delete method is not called.
It's not a bug, the behaviour is documented on the admin actions page. [2]
[1]:
https://docs.djangoproject.
[2]:
https://docs.djangoproject.
--