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

rec*_*hie 19 python django

class PO(models.Model)
    qty = models.IntegerField(null=True)
    cost = models.IntegerField(null=True)
    total = qty * cost
Run Code Online (Sandbox Code Playgroud)

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

Ahs*_*san 37

您可以创建total一个property字段,查看文档

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)
Run Code Online (Sandbox Code Playgroud)

  • 这个问题虽然是你不能通过查询集访问总... ... :( (3认同)
  • 如果值是计算资源密集型的东西,并且您只想在其他字段更改时执行此操作,这也不会有帮助.如果您没有使用实际字段,则没有简单的方法将计算值存储在数据库中. (3认同)

rec*_*hie 13

贾斯汀哈马德斯回答

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

    @property
    def total(self):
        return self.qty * self.cost
Run Code Online (Sandbox Code Playgroud)

  • @MarlinForbes不是`total = property(_get_total)完全相同``@ property`?检查[此处](http://www.artima.com/weblogs/viewpost.jsp?thread=240808). (3认同)