【问题标题】:DJANGO - Computing every item unitprice and quantityDJANGO - 计算每件商品的单价和数量
【发布时间】: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.pyviews.py,您将从那里渲染模板和template
  • @BiploveLamichhane 我发布了我的models.py
  • 你的意思是每个产品每个产品。对吗?
  • 正是@BiploveLamichhane 先生

标签: python django


【解决方案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 %}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-26
    • 2015-04-24
    • 1970-01-01
    • 2017-04-04
    • 2013-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多