由于 Django Admin 中的另一个字段更改而更新布尔字段

Boolean field update due to another field change in Django Admin

我的模特 Department 喜欢:

class Department(models.Model):
    dep_title = models.CharField(max_length=30, verbose_name='Title')
    dep_description = models.CharField(max_length=100, blank=True, verbose_name='Description')
    dep_status = models.BooleanField(default=False, verbose_name='Is Active?')
    dep_start = models.DateField(verbose_name='Date of Establishment')
    dep_end = models.DateField(blank=True, verbose_name='Closing Date', null=True)

DepartmentAdmin

class DepartmentAdmin(admin.ModelAdmin):
    list_display= ('dep_title','dep_description','dep_status', 'dep_start', 'dep_end')

我想检查dep_end日期,如果日期过期,自动设置dep_status = False

我该如何实现?

您可以覆盖您的保存功能。像这样:

class Department(models.Model):
    dep_title = models.CharField(max_length=30, verbose_name='Title')
    dep_description = models.CharField(max_length=100, blank=True, verbose_name='Description')
    dep_status = models.BooleanField(default=False, verbose_name='Is Active?')
    dep_start = models.DateField(verbose_name='Date of Establishment')
    dep_end = models.DateField(blank=True, verbose_name='Closing Date', null=True)
    def save(self, *args, **kwargs):
        if self.dep_end > ## Expiration date here ##:
            self.dep_status = False
        super(Department, self).save(*args, **kwargs)

现在,每次您的模型保存时,它都会检查 dep_end 日期是否已过期。

您还可以将 ModelAdmin 中的 save_model 替换为

from django.contrib import admin
from yourapp.models import Department

class DepartmentAdmin(admin.ModelAdmin):

    def save_model(self, request, obj, form, change):
        super().save_model(request, obj, form, change)
        if change and 'dep_end' in form.changed_data:
            if obj.dep_end < # your expiration date:
                obj.dep_status = False
            else:
                pass

admin.site.register(Department, DepartmentAdmin)

有关 Django-doc

的更多详细信息