Django Admin - 一对多 - 如何确保只有一个 children 选择了布尔字段

Django Admin - One to Many - How to make sure only one children has a boolean field selected

在django中,我有以下模型:

class System(models.Model):
    name = models.CharField(max_length=200)
    """ ... many other fields, not useful for here ..."""
    # Would it make more sense to have the primary instance here ?  
    

class Instance(models.Model):
    name = models.CharField(max_length=200)
    url = models.UrlField(max_length=200)
    system = models.ForeignKey(System, on_delete=models.PROTECT)
    is_production = models.BooleanField()
    

此数据使用管理员进行管理。我想要的是,当系统的一个实例被标记为 is_production 时,该系统的所有其他实例都将其 is_production 字段更新为 False。

此外,我对如何最好地设置此案例的管理员很感兴趣。我将为 edition/creation 个实例使用内联。

但是,我不确定如何确保每个系统在生产中只能有一个实例。

您问了多个问题,但我将重点关注我认为是主要问题的问题:

What I want is that when an instance of the system is marked as is_production, all other instances, for that system have their is_production field updated to False.

覆盖实例模型的保存方法如何?

class Instance(models.Model):
    name = models.CharField(max_length=200)
    url = models.URLField(max_length=200)
    system = models.ForeignKey(System, on_delete=models.PROTECT)
    is_production = models.BooleanField()

    def save(self, *args, **kwargs):
        if self.is_production:
            self.system.instance_set.exclude(id=self.id).update(is_production=False)
        super().save(*args, **kwargs)

这确保无论何时保存 is_production=True 的 Instance 实例,链接到相关 System object 的所有其他 Instance 实例都将其 is_production 值更新为 False。

根据您如何更改实例实例的 is_production 值,这可能适合也可能不适合您想要执行的操作。见 e。 G。此线程讨论如何使用 .update() 方法不会导致调用 save() 方法: (also described in the Django docs,在链接线程中引用)