所以我在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 }}
我的模板看起来像这样
{% 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)
答案 0 :(得分:2)
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 }}
答案 1 :(得分:0)
你没有说哪些观点是你想要使用聚合的观点(我想知道你为什么要发布所有这些观点)。但是,很清楚的是,您从未在任何中传递Expense
对象,并且由于price_sum
是Expense上的实例方法,因此您永远无法访问它。
但实际上你不想这样做。 price_sum
不应该是实例方法,因为它根本不会与实例交互。实际上,如果您尝试从shell运行该方法,您会看到以下错误:
AttributeError: Manager isn't accessible via Expense instances
应该是不言自明的。
您应该定义自定义管理器并在那里定义price_sum方法,而不是这样做。然后你可以访问Expenses.objects.price_sum()
,你可以在上下文中直接传递给你的模板。