获得单价*总数

时间:2014-06-17 18:33:37

标签: python django annotations sum

以下是我的模特的摘录:

class Order(models.Model):
    ...
    content_type = models.ForeignKey(ContentType)
    user = models.ForeignKey('auth.User')


class OrderItem(models.Model):
    ...
    unit_price = models.DecimalField(max_digits=7, decimal_places=2, blank=True)
    quantity = models.SmallIntegerField()
    order = models.ForeignKey(Order)

我有一个仪表板,我想显示已售商品的总数。我正在努力将unit_price乘以quantity

1 个答案:

答案 0 :(得分:2)

  1. 您可以使用extra()查询执行此操作:

    OrderItem.objects.extra(select={'total': 'unit_price * quantity'})
    
  2. 您可以将属性total添加到OrderItem

    class OrderItem(models.Model):
        ...
        unit_price = models.DecimalField(max_digits=7, decimal_places=2, blank=True)
        quantity = models.SmallIntegerField()
    
        @property
        def total(self):
            return unit_price * quantity
    
    # you can then access it like any other field (but you cannot filter on it)
    print OrderItem.objects.get(pk=1).total