Andreas Andreas - 3 months ago 15
Python Question

Custom save method or custom method for adding model fields

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?

Example 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)


Example 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])

Answer

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.