[Django]-Create a field whose value is a calculation of other fields' values

16👍

Justin Hamades answer

class PO(models.Model)
    qty = models.IntegerField(null=True)
    cost = models.IntegerField(null=True)

    @property
    def total(self):
        return self.qty * self.cost
👤rechie

38👍

You can make total a property field, see the docs

class PO(models.Model)
    qty = models.IntegerField(null=True)
    cost = models.IntegerField(null=True)

    def _get_total(self):
       "Returns the total"
       return self.qty * self.cost
    total = property(_get_total)
👤Ahsan

Leave a comment