【发布时间】:2020-09-22 01:49:42
【问题描述】:
我想要计算每件商品的产品而不是总平均值,我如何计算每件商品的单价乘以它的数量?
我只想获取每个项目的总金额,但我该怎么做呢?我应该用什么?聚合还是注释?
我使用聚合来获取所有产品的总量
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>
这是我的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)
【问题讨论】:
-
不要展示你做对了什么...展示你有什么问题。因此,请向我们展示您的相关课程的
models.py、views.py,您将从那里渲染模板和template -
@BiploveLamichhane 我发布了我的models.py
-
你的意思是每个产品,每个产品。对吗?
-
正是@BiploveLamichhane 先生