gpt4 book ai didi

python - 使用 Queryset Model.objects.aggregate(Sum(***)) 对数据库列的所有值求和

转载 作者:太空宇宙 更新时间:2023-11-04 03:58:11 26 4
gpt4 key购买 nike

所以我在 Django 中创建了一个费用表应用程序,我试图获取所有费用的总和,然后我想将其显示在我的模板中。

我的模型:

class Expense(models.Model):
PAYMENT_CHOICES = (
('Cash', 'cash'),
('Credit', 'credit'),
('Debit', 'debit')
)
date = models.DateField()
store = models.CharField(max_length=100)
price = models.DecimalField(max_digits=20, decimal_places=2)
payment_type = models.CharField(max_length=8, choices=PAYMENT_CHOICES)
category = models.CharField(max_length=100)

def __unicode__(self):
return u'%s' % (self.date)

def _price_sum(self):
return self.objects.aggregate(total_price = Sum('price'))

price_sum = property(_price_sum)

我试图在我的模板中使用标签 {{ expenses.price_sum }} 调用“price_sum”

我的模板是这样的

{% if expenses %}
<table class='table table-hover'>
<tr>
<thead>
<th>Date</th>
<th>Store</th>
<th>Price</th>
<th>Payment Type</th>
<th>Category</th>
<th></th>
<th></th>
</thead>
</tr>
{% for expense in expenses %}
<tr>
<tbody>
<td>{{expense.date}}</td>
<td>{{expense.store}}</td>
<td>${{expense.price|floatformat:"2"|intcomma}}</td>
<td>{{expense.payment_type}}</td>
<td>{{expense.category}}</td>
<td>
<form action='{{expense.id}}/' method='get'>
<input type="submit" value="Edit" class="btn">
</form></td>
<td>
<form action='{{expense.id}}/delete/' method='post'>{% csrf_token %}
<input type="submit" value="Delete" class="btn btn-danger" data-dismiss="alert">
</form></td>
</tbody>
</tr>

{% endfor %}

</table>
<h3>Table: {{ expenses.price_sum }}</h3>
{% else %}
<p>No expenses logged.</p>
{% endif %}

我不确定我是否错误地使用了模板标签,或者我的功能是否有误或出了什么问题。我知道这可能真的很简单,但我搜索了整个 StackOverflow、Django 和 Python 文档以及我能找到的任何东西,但我就是想不通。

更新:views.py

from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render
from expenses.models import Expense
from expenses.form import ExpenseForm

def index(request,template='expenses/index.html'):
all_expenses = Expense.objects.all()
return render(request, template, {'all_expenses': all_expenses})

def new(request, template='expenses/new.html'):
if request.method == 'POST':
new_expense = ExpenseForm(request.POST)
if new_expense.is_valid() and new_expense.clean():
new_expense.save()
return HttpResponseRedirect('/expenses/')
else:
new_expense = ExpenseForm()

return render(request, template, {'new_expense':new_expense})

def edit(request, expense_id, template='expenses/edit.html'):
expense = Expense.objects.get(id=expense_id)
if request.method == 'POST':
form = ExpenseForm(request.post, instance=expense)
if form.is_valid and form.clean():
expense = form.save()
return HttpResponseRedirect('/expenses/')
else:
expense = ExpenseForm(instance=expense)

return render(request, template, {'expense':expense})

def delete(request, expense_id):
if request.method == 'POST':
expense = Expense.objects.get(id=expense_id).delete()
return HttpResponseRedirect('/expenses/')
else:
return HttpResponse(status=404)

最佳答案

aggregate 返回看起来像 {'total_price': Decimal('1234')} 的字典。

因此,将 _price_sum 更改如下:

def _price_sum(self):
return self.objects.aggregate(total_price=Sum('price'))['total_price']

或者,如下更改模板:

{{ expenses.price_sum.price_sum }}

关于python - 使用 Queryset Model.objects.aggregate(Sum(***)) 对数据库列的所有值求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17182390/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com