Django 模型:delete() 未触发 [英] Django model: delete() not triggered

查看:21
本文介绍了Django 模型:delete() 未触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型:

class MyModel(models.Model):
 ...
    def save(self):
        print "saving"
        ...
    def delete(self):
        print "deleting"
        ...

save() 方法被触发,但 delete() 没有被触发.我使用最新的 svn-Version(Django 1.2 pre-alpha SVN-11593),以及关于 http://www.djangoproject.com/documentation/models/save_delete_hooks/ 这应该可以工作.有什么想法吗?

The save()-Method is triggered, but the delete() is not. I use the latest svn-Version (Django version 1.2 pre-alpha SVN-11593), and concerning the documentation at http://www.djangoproject.com/documentation/models/save_delete_hooks/ this should work. Any ideas?

推荐答案

我认为您可能正在使用管理员的批量删除功能,并且遇到管理员的批量删除方法不调用 delete 的事实()(见相关ticket).

I think you're probably using the admin's bulk delete feature, and are running into the fact that the admin's bulk delete method doesn't call delete() (see the related ticket).

我过去通过编写用于删除模型的自定义管理操作解决了这个问题.

I've got round this in the past by writing a custom admin action for deleting models.

如果您没有使用管理员的批量删除方法(例如,您点击了对象编辑页面上的删除按钮),那么就会发生其他事情.

If you're not using the admin's bulk delete method (e.g. you're clicking the delete button on the object's edit page) then something else is going on.

此处查看警告:

删除选定对象"操作使用 QuerySet.delete() 提高效率原因,其中有一个重要的警告:模型的 delete() 方法不会被调用.

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.

如果您想覆盖此行为,只需编写一个自定义操作完成删除您的首选方式——例如,通过为每一个调用 Model.delete()所选项目.

If you wish to override this behavior, simply write a custom action which accomplishes 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.

我的自定义管理模型如下所示:

My custom admin model looks like this:

from photoblog.models import PhotoBlogEntry
from django.contrib import admin    

class PhotoBlogEntryAdmin(admin.ModelAdmin):
    actions=['really_delete_selected']

    def get_actions(self, request):
        actions = super(PhotoBlogEntryAdmin, self).get_actions(request)
        del actions['delete_selected']
        return actions

    def really_delete_selected(self, request, queryset):
        for obj in queryset:
            obj.delete()

        if queryset.count() == 1:
            message_bit = "1 photoblog entry was"
        else:
            message_bit = "%s photoblog entries were" % queryset.count()
        self.message_user(request, "%s successfully deleted." % message_bit)
    really_delete_selected.short_description = "Delete selected entries"

admin.site.register(PhotoBlogEntry, PhotoBlogEntryAdmin)

这篇关于Django 模型:delete() 未触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆