我要计算的是每件商品而不是总平均值,如何计算每件商品的单价乘以数量?
我只想获取每个项目的总金额,但是我该怎么做?我应该使用什么?汇总还是注释?
我使用汇总来获取所有产品的总金额
total = CustomerPurchaseOrderDetail.objects.filter(
id__in=cart.values_list('id')
).aggregate(
total=Sum(
F('unitprice') * F('quantity'),
output_field=FloatField(),
)
)['total']
print('aggregate', total)
这是我的逻辑,如何获取每种产品的总金额
total_amount_of_product = CustomerPurchaseOrderDetail.objects.filter(
id__in=cart.values_list('id')).annotate(total_per_item=Sum(F('unitprice') * F('quantity'),
output_field=FloatField(),))
item_totals = [item.total_per_item for item in total_amount_of_product]
这是我的html中的结果
这就是我打印到html的方式
<td class="cart__cell--total"><span class="cart__item-total">₱ {{item_totals}}</span></td>
这是我的模特。py
class CustomerPurchaseOrderDetail(models.Model):
profile = models.ForeignKey(Customer,
on_delete=models.SET_NULL, null=True, blank=True,
verbose_name="Client Account")
products = models.ForeignKey(Product,
on_delete=models.SET_NULL, null=True, blank=True,
verbose_name="Product")
quantity = models.IntegerField(null=True, blank=True, default=1)
unitprice = models.FloatField(max_length=500, null=True, blank=True)
amount = models.FloatField(max_length=500, null=True, blank=True)
答案 0 :(得分:1)
您可以在models.py
中添加一个方法以返回所需的内容:
class CustomerPurchaseOrderDetail(models.Model):
profile = models.ForeignKey(Customer, on_delete=models.SET_NULL,null=True, blank=True,verbose_name="Client Account")
products = models.ForeignKey(Product,on_delete=models.SET_NULL, null=True, blank=True,verbose_name="Product")
quantity = models.IntegerField(null=True, blank=True, default=1)
unitprice = models.FloatField(max_length=500, null=True, blank=True)
amount = models.FloatField(max_length=500, null=True, blank=True)
@property
def totalAmountOfProduct(self):
return self.unitprice * self.quantity
在您的views.py:
all_products = CustomerPurchaseOrderDetail.objects.all()
在您的模板中:
{% for item in all_products %}
<td class="cart__cell--total"><span class="cart__item-total">₱ {{item.totalAmountOfProduct}}
{% endfor %}