这是我的代码:
楷模:
class Category(models.Model):
name = models.CharField(max_length=100)
def get_month_sum_series(self):
return [('2012-01-01',100)]
class Operation(models.Model):
date = models.DateField()
value = models.DecimalField(max_digits = 9, decimal_places = 2)
category = models.ForeignKey(Category, null = True)
comments = models.TextField(null = True)
视图.py:
from django.template import Context, loader
from accounts.models import Category, Operation
from django.http import HttpResponse
from django.db.models import Sum, Max
def index(request):
category_list = Category.objects.all().annotate(suma = Sum('operation__value'))
template = loader.get_template('reports/index.html')
context = Context({
'category_list' : category_list,
})
return HttpResponse(template.render(context))
模板:
{% if category_list %}
<table>
{% for category in category_list %}
<tr><td><a href="{{ category.id }}/">{{ category.name }}</a></td><td style="text-align:right">{{ category.suma|default:0|currency }}</td>
{% for month_sum in category.get_month_sum_series %}
<td>{{ month_sum.1|default:0|currency }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
{% else %}
{% endif %}
category.get_month_sum_series 不起作用....
但是如果我改变
category_list = Category.objects.all().annotate(suma = Sum('operation__value'))
进入
category_list = Category.objects.all()
category.get_month_sum_series 不起作用.....(但当然是注释部分 - 不是)
如何更改 category_list 或 view 以获取它们?