django重写model的delete方法 | 阿小信的博客
阿小信大人的头像
Where there is a Python, there is a way. 阿小信大人

django重写model的delete方法2014-10-09 17:47

重写model的save方法没什么问题,毕竟save就只能那样save

def save(self, *args, **kwargs):
    do_something()
    super(Blog, self).save(*args, **kwargs) # Call the "real" save() method.
    do_something_else()

但是重写delete时会有两种情况,一种是点进每条记录里再点删除,另外一种是在外面的列表里面删除所有选中的记录, 直接在model中重写delete只会在第一种情况下有空,在第二种情况下是无法工作的,因为第二种删除使用的queryset;

Overridden model methods are not called on bulk operations
Note that the delete() method for an object is not necessarily called when deleting objects in bulk using a QuerySet. 
To ensure customized delete logic gets executed, you can use pre_delete and/or post_delete signals.

Unfortunately, there isn’t a workaround when creating or updating objects in bulk, since none of save(), pre_save, and post_save are called.

所以不仅要在model中重写delete:

def delete(self):
    do_something()
    super(Blog, self).delete()

还需要在modeladmin中重写这个delete_selected action

def delete_selected(modeladmin, request, queryset):
do_something()
for i in queryset:
    i.delete()
delete_selected.short_description = '删除已选项'

class BlogAdmin(admin.ModelAdmin):
    actions = [delete_selected]

如果您觉得从我的分享中得到了帮助,并且希望我的博客持续发展下去,请点击支付宝捐赠,谢谢!

若非特别声明,文章均为阿小信的个人笔记,转载请注明出处。文章如有侵权内容,请联系我,我会及时删除。

#Python#   #django
分享到:
阅读[2559] 评论[0]

你可能也感兴趣的文章推荐

本文最近访客

发表评论