Django-不支持的操作数类型/:' dict'和' dict'

时间:2015-10-26 02:06:49

标签: python html django

我怀疑如何显示"净利润"在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"?  

2 个答案:

答案 0 :(得分:2)

如果是这样的话:

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

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

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

答案 1 :(得分:1)

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

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']