8

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)
broinjc
  • 2,619
  • 4
  • 28
  • 44

2 Answers2

22

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

karthikr
  • 97,368
  • 26
  • 197
  • 188
  • Thank you, this worked perfectly for me... Now I am trying to interpret `models.BooleanField` as 0 or 1 integers to add up and score. – broinjc Mar 04 '14 at 00:18
  • Just do `sum([...])` Example: `sum([True, False, True, True])` = 3 – karthikr Mar 04 '14 at 01:40
10

How about this?

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

     @property
     def score(self):
         return self.x + self.y + self.z

Official docs on Model Methods here

Daryl Lukas
  • 155
  • 2
  • 10