Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Model field based on other fields?

Tags:

django

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)
like image 902
broinjc Avatar asked Mar 03 '14 21:03

broinjc


2 Answers

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

like image 199
karthikr Avatar answered Sep 19 '22 14:09

karthikr


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

like image 27
Daryl Lukas Avatar answered Sep 23 '22 14:09

Daryl Lukas