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])
save() method from its parent class is to be overridden so we use super keyword. slugify is a function that converts any string into a slug. so we are converting the title to form a slug basically.
Saving objects. To save an object back to the database, call save() : Model.
To save data in Django, you normally use . save() on a model instance. However the ORM also provides a . update() method on queryset objects.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With