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

前端 未结 2 1556
长发绾君心
长发绾君心 2020-12-14 18:11
class PO(models.Model)
    qty = models.IntegerField(null=True)
    cost = models.IntegerField(null=True)
    total = qty * cost

How will I solve <

相关标签:
2条回答
  • 2020-12-14 18:40

    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)
    
    0 讨论(0)
  • 2020-12-14 18:51

    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
    
    0 讨论(0)
提交回复
热议问题