'How to add two fields of django model and save the sum in another field?

class example(models.Model):
    var1 = models.IntegerField(default=0)
    var2 = models.IntegerField(default=0)
    var3 = models.IntegerField(default=0)

    sum = var1 + var2 + var3

Can anyone help me to save the sum of the three field and save it in the sum field of the model?



Solution 1:[1]

If you want to save the field to the DB:

class example(models.Model):
    var1 = models.IntegerField(default=0)
    var2 = models.IntegerField(default=0)
    var3 = models.IntegerField(default=0)

    sum = models.IntegerField(...)

    def save(self):
        self.sum = self.var1 + self.var2 + self.var3
        return super(example, self).save()

or if you want it to just be a calculation in memory but not stored in the DB (Recommended):

class example(models.Model):
    var1 = models.IntegerField(default=0)
    var2 = models.IntegerField(default=0)
    var3 = models.IntegerField(default=0)

    @property
    def sum(self):
        sum = self.var1 + self.var2 + self.var3
        return sum

Wrapping a method in property essentially makes it so that you don't use parentheses to call it. It's really just a syntax difference. This is recommended because you want to avoid redundant data. Think about what would happen when you update one of the vars but an error occurs before the sum gets updated? Now your database is in an invalid state because sum doesn't reflect reality. So it's better to do a computation at runtime. However, you may want to store it to save on performance if the computation is a huge one.

Example, assume a as an instance of example:

a = example()
a.var2 = 3
a.var1 = 2

If sum is a method with the @property decorator:

print(a.sum) # outputs 5
print(a.sum()) # Never tried this but I think it would error?

If sum is just a regular method without @property decorator

print(a.sum()) # outputs 5
print(a.sum) # outputs a method pointer

NOTE: I've never actually tried this to verify but I don't think you can wrap methods in @property if they have other parameters besides self. That wouldn't really make sense since the whole point is that it shortens the call.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1