使用额外参数覆盖 django model.py 的删除方法

发布于 2024-10-14 20:54:28 字数 118 浏览 2 评论 0原文

我有一个带有接受 2 个参数的删除方法的模型。我需要重写什么才能确保我的自定义删除方法是从 django admin 调用的方法?我使用的版本仍然没有 delete_model 所以我无法使用它。

I have a Model with a delete method that accepts 2 arguments. What do I need to override to make sure my custom delete method is what is called from django admin? The version am using still doesn't have delete_model so I cant use that.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

冷默言语 2024-10-21 20:54:28

我最终做的是编写自己的自定义删除操作,该操作使用我的自定义删除方法,而不是使用查询集的批量删除

class MyModelAdmin(admin.ModelAdmin):
    actions  = ['custom_delete_selected',]

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

    def custom_delete_selected(self, request, queryset):
        #Meant to cancel the default delete operation in admin page
        #so that the system uses the model's delete method instead of queryset.delete 
        for obj in queryset:
            obj.delete("param1", "param2")

        if queryset.count() == 1:
            message_bit = "1 item was"
        else:
            message_bit = "%s items were" % queryset.count()
        self.message_user(request, "%s successfully deleted." % message_bit)

    custom_delete_selected.short_description = "Delete selected items"

What I ended up doing was writing my own custom delete action that made use of my custom delete method instead of using the queryset's bulk delete

class MyModelAdmin(admin.ModelAdmin):
    actions  = ['custom_delete_selected',]

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

    def custom_delete_selected(self, request, queryset):
        #Meant to cancel the default delete operation in admin page
        #so that the system uses the model's delete method instead of queryset.delete 
        for obj in queryset:
            obj.delete("param1", "param2")

        if queryset.count() == 1:
            message_bit = "1 item was"
        else:
            message_bit = "%s items were" % queryset.count()
        self.message_user(request, "%s successfully deleted." % message_bit)

    custom_delete_selected.short_description = "Delete selected items"

you need to use Django 1.3 which has a delete_model method with 3 arguments

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文