【问题标题】:Getting the total of unit price * quantity获取单价*数量的总和
【发布时间】:2014-06-17 18:33:37
【问题描述】:

这是我的模型的摘录:

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

【问题讨论】:

  • 这只是您想要的OrderItem 级别的东西吗?或者您想获得Order 上所有OrderItems 的总和(单位价格* 数量)?
  • @pcoronel 在 OrderItem 级别,而不是每个订单。

标签: python django annotations sum


【解决方案1】:
  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
    

【讨论】:

    猜你喜欢
    • 2022-01-06
    • 1970-01-01
    • 2017-04-04
    • 2020-07-20
    • 2021-07-07
    • 1970-01-01
    • 2019-08-15
    • 1970-01-01
    • 2014-07-18
    相关资源
    最近更新 更多