[英]how can I get the sum of all expense based on current logged user in django?
I am using to sum all the expense values which are assigned to an user.我用来汇总分配给用户的所有费用值。 I am not able to display it in my webpage.
我无法在我的网页中显示它。 How can i do that?
我怎样才能做到这一点? The models.py code is as follows:
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视图.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 CODE: 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>
You assign this to the Expense
variable, so you render this with Expense
, so not Expense.expenses
, you already "unwrapped" the value from the dictionary:您将其分配给
Expense
变量,因此您使用Expense
渲染它,而不是Expense.expenses
,您已经“解包”了字典中的值:
{{
Expense }}
Note : When you make calculations with money, it is better to use a
DecimalField
[Django-doc] , not aFloatField
[Django-doc] .注意:当你用钱进行计算时,最好使用
DecimalField
[Django-doc] ,而不是FloatField
[Django-doc] 。 Floats can generate rounding errors when you perform calculations.执行计算时,浮点数会产生舍入误差。 You can also use
django-money
[GitHub] to specify aMoneyField
.你也可以使用
django-money
[GitHub]来指定一个MoneyField
。 This has also specifies a currency, and can convert money to a different currency.这也指定了一种货币,并且可以将货币转换为不同的货币。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.