Django模型:delete()未触发

我有一个模型:

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

save() – 方法被触发,但delete()不是。我使用最新的svn版本(Django版本1.2 pre-alpha SVN-11593),并关于http://www.djangoproject.com/documentation/models/save_delete_hooks/的文档这应该工作。
有任何想法吗?

我想你可能使用管理员的批量删除功能,而且管理员的批量删除方法不调用delete()(见相关ticket)。

我过去通过编写一个自定义的管理动作删除模型。

如果您没有使用管理员的批量删除方法(例如,您点击对象的修改页面上的删除按钮),则会发生其他情况。

参见警告here

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,
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 07002.

我的自定义管理模型看起来像这样:

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)
http://stackoverflow.com/questions/1471909/django-model-delete-not-triggered

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:Django模型:delete()未触发