DJANGO: USE DELETE SIGNALS INSTEAD OF OVERRIDING MODEL.DELETE() METHOD

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.com/en/dev/topics/db/queries/#deleting-objects
[2]: 
https://docs.djangoproject.com/en/dev/ref/contrib/admin/actions/#admin-actions

-- 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值