Regis Santos
Regis Santos

Reputation: 3749

Record Total Value in Django

Record the value of a calculated field is really more efficient to calculate without saving?

class SaleDetail(models.Model):
    product = models.ForeignKey(Product)
    quantity = models.IntegerField()
    price = models.DecimalField(max_digits=8, decimal_places=2)
    subtotal = models.DecimalField(max_digits=8, decimal_places=2)

    def save(self, *args, **kwargs):
        self.subtotal = self.price * self.quantity
        super(SaleDetail, self).save(*args, **kwargs)

Calculated field

class SaleDetail(models.Model):
    product = models.ForeignKey(Product)
    quantity = models.IntegerField()
    price = models.DecimalField(max_digits=8, decimal_places=2)

    def get_total_value(self):
        if self.quantity:
            return self.price * self.quantity

    total_value = property(get_total_value)

Upvotes: 0

Views: 32

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 600051

There doesn't really seem to be any good reason to pre-calculate the field here. Multiplying one existing value by another is a simple operation, and there's no benefit to be gained by calculating it on save.

There would only be some benefit if the value to be calculated involved a lot of complex and expensive operations, such as querying multiple tables or calling an external API.

Upvotes: 1

Related Questions