首页 > 解决方案 > 当检查布尔字段修改数据库中的其他表时,django-django admin 中的 List_editable

问题描述

我想问一个关于 django-admin 中 list_editable 列的问题。如果我有这样的事情:

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

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

标签: djangodjango-rest-frameworkdjango-admin

解决方案


对于您的用例,管理员操作可能更合适。

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

更改列表操作示例

假设您希望能够在 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 admin 中,当您选择员工并选择开始/结束休假操作时,上述方法将更新数据库中的对象,更改列表视图将显示is_on_vacation列的更新值。

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


推荐阅读