创建一个字段,其值是其他字段值的计算

时间:2012-07-13 06:32:30

标签: python django

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

我将如何解决上述total = qty * cost。我知道它会导致错误,但不知道如何解决这个问题。

2 个答案:

答案 0 :(得分:36)

您可以total property字段,请参阅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)

答案 1 :(得分:12)

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