Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django model, Overriding the save method or custom method with property

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])
like image 650
Andreas Avatar asked Sep 06 '16 17:09

Andreas


People also ask

How do I override a save in Django?

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.

Which method is used to save a model in DB in Python Django?

Saving objects. To save an object back to the database, call save() : Model.

How do I save changes in Django 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.


1 Answers

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.

like image 163
Andrey Rusanov Avatar answered Sep 19 '22 17:09

Andrey Rusanov