我正在尝试以html输出基于2个聚合(总和)的计算 虽然,它不会显示(典型错误)。有人可以帮我吗?
在views.py中:(提取)
def calcul(request, slug):
numerator = CF.objects.filter(type='inflow').aggregate(sum=Sum('amount'))
calculation = numerator / Main.objects.filter(slug=slug).aggregate(sum=Sum('total')
return render(request, 'home/detail.html', { 'calculation' : calculation})
在我的模板中:
{{ calculation }}
答案 0 :(得分:1)
聚合返回字典,因此您应该取出值然后进行计算:
def calcul(request, slug):
numerator = CF.objects.filter(type='inflow').aggregate(sum=Sum('amount'))
calculation = numerator['sum'] / Main.objects.filter(slug=slug).aggregate(sum=Sum('total')['sum']
return render(request, 'home/detail.html', { 'calculation' : calculation})
答案 1 :(得分:1)
您的aggregation将输出字典,如果在其后添加print(numerator)
,则会看到字典{'sum': <value>}
(与分母相同)。
您需要访问该值,然后使用它:
def calcul(request, slug):
numerator = CF.objects.filter(type='inflow').aggregate(sum=Sum('amount'))['sum']
denominator = Main.objects.filter(slug=slug).aggregate(sum=Sum('total'))['sum']
try:
calculation = numerator / denominator
except ZeroDivisionError:
calculation = 0
return render(request, 'home/detail.html', { 'calculation' : calculation})