python 提升生活和办公效率

2020-02-15 [django] admin ‘删除所选’

2020-02-15  本文已影响0人  alue

有些模型,我们会自定义delete()方法,例如在删除用户信息的同时,将对应的账号也一起删除

# 自定义用户信息模型的删除方法
    def delete(self, using=None, keep_parents=False):
        user = self.user
        super().delete(using, keep_parents)
        user.delete()

但是注意了,官网明确指出了

Warning
The “delete selected objects” action uses QuerySet.delete() for efficiency reasons, which has an important caveat: your model’s delete() method will not be called.
If you wish to override this behavior, you can override ModelAdmin.delete_queryset() or write a custom action which does deletion in your preferred manner – for example, by calling Model.delete() for each of the selected items.
For more background on bulk deletion, see the documentation on object deletion.

大意是,如下图所示,django为了提高批量删除的效率,如果我们用admin后台自带的选中删除功能,上面自定义的delete()方法不会被执行.

这种action删除方法不会调用模型自定义的delete方法

官方给出的解决方法是重载 ModelAdmin.delete_queryset()或者自定义action。

# 在admin类下重载块删除方法
    def delete_queryset(self, request, queryset):
        for obj in queryset:
            obj.delete()

当然还有一种方法是利用信号signals, 官网给出的说明是

The delete() method does a bulk delete and does not call any delete() methods on your models. It does, however, emit the pre_delete and post_delete signals for all deleted objects (including cascaded deletions).

通过定义pre_delete 或者post_delete 监听事件,完成相关对象的操作。

上一篇下一篇

猜你喜欢

热点阅读