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>The answer depends on the way you are going to use sum_integers. If you keep it as a field in DB, you will be able to make a queries on it, and with property it would be very tricky. </p>

<p>On other hand, if you aren't going to make a queries and this data does not valuable for you(in other words - you need sum_integers as data representation)
then you should go with property.</p>

<p>From the point of the application performance:
If you are going to make complex operations on thousands of objects - it might be better to store the value in column or at least change property to <a href="https://docs.djangoproject.com/es/1.10/ref/utils/#django.utils.functional.cached_property" rel="nofollow">cached_property</a> if it is called a few times.</p>

<p>As a summary - storing value of sum in DB column is more universal and doesn't have any downgrades, but in some cases <code>property</code> approach allows you to keep your data model cleaner and saves some space on your disk.</p>

<p>I hope it is an answer on your question. Please fill free to ask question if something is unclear.</p>

python django django-models