我使用的是分配给用户的所有费用值的总和。我无法在我的网页上显示它。我怎么能做到呢?models.py代码如下:
class expense(models.Model):
Expensecat=(('food','Food'),
('transportation','Transportation'),
('education','Education'),
('health','Health'),
('clothes','Clothes'),
('beauty','Beauty'),
('hosuehold','Household'),
)
ExpenseAmount=models.FloatField(max_length=100)
Category=models.CharField(max_length=200,choices= Expensecat)
Description=models.TextField(max_length=200)
Date=models.DateTimeField(default=timezone.now)
user=models.ForeignKey(User,on_delete=models.CASCADE)
Views.py
def home(request):
try:
expense_total = expense.objects.filter(user=request.user).aggregate(expenses=Sum('ExpenseAmount'))
except TypeError:
print('No data')
data = {
'Expense':expense_total['expenses'],
}
return render(request, 'budget/home.html', data )
HTML代码:
<div class="col-lg-3 col-md-6 d-flex stat my-3">
<div class="mx-auto">
<h6 class="text-muted">Expense</h6>
<h3 class="font-weight-bold">{{ Expense.expenses }}</h3>
<h6 class="text-success"></h6>
</div>
您将其分配给Expense
变量,因此您将其渲染为Expense
,而不是Expense.expenses
,因为您已经"unwrapped&;字典中的值:
{{Expense}}
注意:当你用金钱做计算时,最好使用
DecimalField
(Django-doc),FloatField
[Django-doc]。浮点数在执行计算时可能会产生舍入错误。您也可以使用django-money
[GitHub]指定一个MoneyField
。这还指定了一种货币,并可以将货币转换成不同的货币货币。