以下是我的模特的摘录:
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
。
答案 0 :(得分:2)
您可以使用extra()
查询执行此操作:
OrderItem.objects.extra(select={'total': 'unit_price * quantity'})
您可以将属性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