List_editable 在 django-django admin 中检查布尔字段时修改数据库中的其他表

List_editable in django-django admin when check a boolean field modify other tables in database

我想问一个关于django-admin中list_editable栏的问题。 如果我有这样的东西:

class fooAdmin(admin.ModelAdmin):
    list_display = ('name', 'age', 'boolean_field')
    list_editable = ('boolean_field')

当我启用(或禁用)这个 list_editable 字段时,我是否可能触发一些修改数据库中其他 table 的东西?例如如果 boolean_field 被选中并且我保存它,自动添加或删除另一个 table 中的一行? 提前致谢。

对于您的用例,admin action 可能更合适。

用户将 select 他们想要在更改列表页面上修改的行,然后选择要对这些行执行的操作。举例说明:

假设您希望能够 select django 管理员中的员工并将他们标记为“休假”或“休假”。度假模式可能如下所示:

# models.py
class Employee(models.Model):
    name = models.CharField(max_length=255)
    age = models.IntegerField()

    def is_on_vacation(self):
        """ Returns true if the employee is on vacation, otherwise false. """
        return self.vacation_set.filter(end_date__isnull=True).exists()

class Vacation(models.Model):
    employee = models.ForeignKey("Employee")
    start_date = models.DateTimeField(auto_now_add=True)
    end_date = models.DateTimeField(blank=True, null=True)

admin.py 中,我们将设置一个操作来开始和结束员工的假期:

# admin.py
from django.utils import timezone

class EmployeeAdmin(admin.ModelAdmin):
    # Adding is_on_vacation here will show a true/false column in the change list
    # that displays the output of the Employee.is_on_vacation method.
    list_display = ("name", "age", "is_on_vacation")

    def start_vacation(self, request, queryset):
        for employee in queryset:
            Vacation.objects.create(employee=employee)

        self.message_user(
            request,
            f"Successfully started vacations for {len(queryset)} employees",
        )

    start_vacation.short_description = "Start vacations for selected employees"

    def end_vacation(self, request, queryset):
        for employee in queryset:
            vacation = employee.vacation_set.filter(end_date__isnull=True).first()
            vacation.end_date = timezone.now()
            vacation.save()

        self.message_user(
            request,
            f"Successfully ended vacations for {len(queryset)} employees",
        )

    end_vacation.short_description = "End vacations for selected employees"

现在在 django 管理中,当你 select 员工和 select start/end 休假操作时,上面的方法将更新数据库中的对象,更改列表视图将显示 is_on_vacation 列的更新值。

注意:上面的示例代码没有执行任何错误检查,应该进行优化以进行批量查询。