2020-02-15 [django] admin ‘删除所选’
有些模型,我们会自定义
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 usesQuerySet.delete()
for efficiency reasons, which has an important caveat: your model’sdelete()
method will not be called.
If you wish to override this behavior, you can overrideModelAdmin.delete_queryset()
or write a custom action which does deletion in your preferred manner – for example, by callingModel.delete()
for each of the selected items.
For more background on bulk deletion, see the documentation on object deletion.
大意是,如下图所示,django为了提高批量删除的效率,如果我们用admin后台自带的选中删除功能,上面自定义的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 anydelete()
methods on your models. It does, however, emit thepre_delete
andpost_delete
signals for all deleted objects (including cascaded deletions).
通过定义pre_delete
或者post_delete
监听事件,完成相关对象的操作。