Django model, Overriding the save method or custom method with property
<p>I'm working with some models that has to return a sum of model fields. Is it better to override the save method on the model or just create a custom method that returns the sum. Is there any performance issues with either of the solutions?</p>

<p>Example 1, overriding the save method.</p>

<pre><code>class SomeModel(models.Model):
    integer1 = models.IntegerField()
    integer2 = models.IntegerField()
    integer3 = models.IntegerField()

    sum_integers = models.IntegerField()

    def save(self, *args, **kwargs):
        self.sum_integers = sum(
            [self.integer1, self.integer2, self.integer3])
        self.sum_integers.save()
        return super(SomeModel, self).save(*args, **kwargs)
</code></pre>

<p>Example 2, custom method</p>

<pre><code>class SomeModel(models.Model):
    integer1 = models.IntegerField()
    integer2 = models.IntegerField()
    integer3 = models.IntegerField()

    @property
    def sum_integers(self):
       return sum([self.integer1, self.integer2, self.integer3])
</code></pre>

<p>Depends on whether you have to update the fields more or call the sum more.</p>

<p>I am assuming, to make it more generic, that the operation is not only addition but multiple complex calculation involving large numbers.</p>

<p>If you have to get the sum every now and then, then its better to create a model field and add value on save.</p>

<p>If you have to update it mostly, then normally getting the value on call (the second method) is more apt.</p>

python django django-models