rechie
rechie

Reputation: 2217

Create a field whose value is a calculation of other fields' values

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

How will I solve total = qty * cost above. I know it will cause an error, but have no idea of how to deal with this.

Upvotes: 21

Views: 16927

Answers (2)

rechie
rechie

Reputation: 2217

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

Upvotes: 16

Ahsan
Ahsan

Reputation: 11832

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)

Upvotes: 38

Related Questions