Search code examples
pythondjangobooleanmodels

Python - Django - Model BooleanField Dependent On Other BooleanField In Same Model


I am using Django to write a web application and would like to know if it is possible to have a BooleanField within a model for which the value will be based on other BooleanFields in the same model.

Basically, I would like one BooleanField in the model to be True only if all other BooleanFields in the model are True.

For example, with the Model below:

class ModelEx(models.Model):
   booleanA = models.BooleanField(default=False)
   booleanB = models.BooleanField(default=False)
   booleanC = models.BooleanField(default=False)
   booleanD = models.BooleanField(default=False)

I would like booleanA to be True only if booleanB and booleanC and booleanD are True.

I have not found any information about this so it would be great if anyone knew if there is a solution for this.

Thanks.


Solution

  • You can override the save method of your model.

    class ModelEx(models.Model):
       booleanA = models.BooleanField(default=False)
       booleanB = models.BooleanField(default=False)
       booleanC = models.BooleanField(default=False)
       booleanD = models.BooleanField(default=False)
    
       def save(self, *args, **kwargs):
           self.booleanA = self.booleanA and self.booleanB and self.booleanC
           return super(ModelEx, self).save(*args, **kwargs)