django - 当检查布尔字段修改数据库中的其他表时,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 被选中并且我保存它,自动添加或删除另一个表中的一行?提前致谢。
解决方案
对于您的用例,管理员操作可能更合适。
用户将在更改列表页面上选择他们想要修改的行,然后选择对这些行执行的操作。举例说明:
假设您希望能够在 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
列的更新值。
注意:上面的示例代码不执行任何错误检查,应进行优化以进行批量查询。
推荐阅读
- php - 将对象转换为数组并获取其值
- r - 在R中的每一行中提取次要等位基因计数
- powershell - 在 PowerShell 中共享路径后切断完整路径
- excel - 在字段之间插入空行或移动条目
- c++ - 节点 12 (v8) - 将弃用的代码转换为“可能”版本
- machine-learning - 深度神经网络 - 要调整的参数顺序
- wordpress - Safari 不加载图片
- javascript - 不使用 MailComposer 和 Nodemailer 发送 BBC 电子邮件
- apache - 找不到虚拟主机对象
- javascript - 使用 vanilla JS 将 rel="noopener noreferrer nofollow" 添加到所有外部链接的最佳方法