python – Django:将模型方法暴露给管理员

示例型号:

class Contestant(models.Model):
    first_name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255)
    email = models.EmailField()
    ...

    def send_registration_email(self):
        ...

我希望能够将此方法公开给管理员,以便管理员可以登录并手动调用它.我正在考虑尝试属性属性,但不确定这是否会起作用.还有可能公开这样的方法,它接受除self以外的参数,可能是select或者某些东西的相关对象吗?

最佳答案 您可以将其注册为
admin action.

from django.contrib import admin
from myapp.models import Contestant

def send_mail(modeladmin, request, queryset):
    for obj in queryset:
        obj.send_registration_email()

make_published.short_description = "Resend activation mails for selected users"

class ContestantAdmin(admin.ModelAdmin):
    list_display = [...]
    ordering = [...]
    actions = [send_mail]

admin.site.register(Contestant, ContestantAdmin)
点赞