Django - 输出一个计算
Django - output a calculation
我正在尝试在 html 中输出一个基于 2 个聚合(总和)的计算
虽然,它不显示(typerror)。有人可以帮我吗?
在 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 }}
聚合returns字典所以你应该把值取出来然后做计算:
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})
你的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})
我正在尝试在 html 中输出一个基于 2 个聚合(总和)的计算 虽然,它不显示(typerror)。有人可以帮我吗?
在 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 }}
聚合returns字典所以你应该把值取出来然后做计算:
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})
你的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})