Reputation: 1099
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?
Option 1: Overriding the save method.
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)
Option 2: Custom method
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])
Upvotes: 8
Views: 2137
Reputation: 2394
Depends on whether you have to update the fields more or call the sum more.
I am assuming, to make it more generic, that the operation is not only addition but multiple complex calculation involving large numbers.
If you have to get the sum every now and then, then its better to create a model field and add value on save.
If you have to update it mostly, then normally getting the value on call (the second method) is more apt.
Upvotes: 2
Reputation: 4606
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.
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.
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 cached_property if it is called a few times.
As a summary - storing value of sum in DB column is more universal and doesn't have any downgrades, but in some cases property
approach allows you to keep your data model cleaner and saves some space on your disk.
I hope it is an answer on your question. Please fill free to ask question if something is unclear.
Upvotes: 4