当前位置: 代码迷 >> python >> Django不支持/的操作数类型:“ dict”和“ dict”
  详细解决方案

Django不支持/的操作数类型:“ dict”和“ dict”

热度:117   发布时间:2023-06-16 10:20:14.0

我怀疑如何在html中显示“净利润”的结果,这是net_profit / sales的结果。 我不想将此除法公式直接放在html中,因为除此之外还有许多其他复杂的计算。

那么如何将这种划分结果同时放在views.py和html中?

以下代码将错误作为标题返回。

views.py

def get_context_data(self, **kwargs):
        context = super(XXXView, self).get_context_data(**kwargs)
        context["sales"] = self.get_queryset().aggregate(Sum('sales'))
        context["net_profit"] = self.get_queryset().aggregate(Sum('net_profit'))

        context["net_margin"] = context["net_profit"]/context["sales"]  ---if here correct--?

HTML

to show result for sales: {{sales.sales__sum}}
to show result for net_profit: {{net_profit.net_profit__sum}}
how to show result for "net margin"?  

如果这样:

sales = context['sales']
net_profit = context['net_profit']

销售和净利润是对象。 因此,html show的净利润为{{ sales.sale__sum/ net_profit.net_profit__sum }}

django模板可以使用数字校准。

您的查询不返回数字值,而是一个字典:

context["sales"] = self.get_queryset().aggregate(Sum('sales'))
#{'sales__sum': Decimal('123123')}    
context["net_profit"] = self.get_queryset().aggregate(Sum('net_profit'))
#{'net_profit__sum': Decimal('123123')}

您应该过滤捕获字典值:

result = context['sales']['sales__sum'] / context['net_profit']['net_profit__sum']