【问题标题】:List_editable in django-django admin when check a boolean field modify other tables in database当检查布尔字段修改数据库中的其他表时,django-django admin 中的 List_editable
【发布时间】:2021-04-17 12:34:45
【问题描述】:

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

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

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

【问题讨论】:

    标签: django django-rest-framework django-admin


    【解决方案1】:

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

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

    假设您希望能够在 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 列的更新值。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 2015-09-03
      • 2021-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多