Search code examples
django

Model field based on other fields?


Can I have a model field be based on other fields? For example:

class Foo(models.Model):
    x = models.PositiveSmallIntegerField()
    y = models.PositiveSmallIntegerField()
    z = models.PositiveSmallIntegerField()

    score = models.PositiveSmallIntegerField(default=x+y+z)

Solution

  • Yes, the best way to handle this would be to override the save method of the model

    class Foo(models.Model):
        x = models.PositiveSmallIntegerField()
        y = models.PositiveSmallIntegerField()
        z = models.PositiveSmallIntegerField()
    
        score = models.PositiveSmallIntegerField()
    
        def save(self, *args, **kwargs):
            self.score = self.x + self.y + self.z
            super(Foo, self).save(*args, **kwargs) # Call the "real" save() method.
    

    Make sure you take care of the necessary validations.

    More on this here: official documentation