Django 管理员:覆盖删除方法 [英] Django admin: override delete method

查看:26
本文介绍了Django 管理员:覆盖删除方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 admin.py 如下:

I have admin.py as follows:

  class profilesAdmin(admin.ModelAdmin):
     list_display = ["type","username","domain_name"]

现在我想在删除对象之前执行一些操作:

Now i want to perform some action before deleting the object:

  class profilesAdmin(admin.ModelAdmin):
     list_display = ["type","username","domain_name"]

     @receiver(pre_delete, sender=profile)
     def _profile_delete(sender, instance, **kwargs):
        filename=object.profile_name+".xml"
        os.remove(os.path.join(object.type,filename))

如果我使用这样的删除信号方法,我会收到一条错误消息,提示 self 应该是第一个参数.

If i use delete signal method like this I get an error saying self should be the first parameter.

如何修改上述功能?
我想检索被删除对象的 profile_name.如何做到这一点?

How can I modify the above function?
And I want to retrieve the profile_name of the object being deleted. How can this be done?

我也尝试过覆盖 delete_model 方法:

I also tried overriding delete_model method:

def delete_model(self, request, object):
    filename=object.profile_name+".xml"
    os.remove(os.path.join(object.type,filename))
    object.delete()

但如果必须一次删除多个对象,则此方法不起作用.

But this dosn't work if multiple objects have to be deleted at one shot.

推荐答案

您的 delete_model 方法走在了正确的轨道上.当 django 管理员一次对多个对象执行操作时,它使用 更新函数.但是,正如您在文档中看到的,这些操作仅使用 SQL 在数据库级别执行.

You're on the right track with your delete_model method. When the django admin performs an action on multiple objects at once it uses the update function. However, as you see in the docs these actions are performed at the database level only using SQL.

您需要将 delete_model 方法添加为 自定义操作.

You need to add your delete_model method in as a custom action in the django admin.

def delete_model(modeladmin, request, queryset):
    for obj in queryset:
        filename=obj.profile_name+".xml"
        os.remove(os.path.join(obj.type,filename))
        obj.delete()

然后将你的函数添加到你的模型管理员 -

Then add your function to your modeladmin -

class profilesAdmin(admin.ModelAdmin):
    list_display = ["type","username","domain_name"]
    actions = [delete_model]

这篇关于Django 管理员:覆盖删除方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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