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

2024-04-19 15:02:35 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我将如何解决上面的total = qty * cost。我知道这会导致错误,但不知道如何处理。


Tags: truemodelmodels错误nullpoclasstotal
2条回答

您可以将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)

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

相关问题 更多 >