模板中的Django-重新分组后的列表总数
我在模板中使用Django根据category字段重新组合多维列表。对于每个类别,我还需要来自同一列表的整数字段的总和。我已经阅读了很多关于这方面的问题,在模板呈现之前,我似乎必须在视图中完成这项工作。然而,这意味着我必须分别定义每个类别的总数,而我希望重组可以避免这个麻烦。有没有其他更好的方法模板中的Django-重新分组后的列表总数,django,templates,Django,Templates,我在模板中使用Django根据category字段重新组合多维列表。对于每个类别,我还需要来自同一列表的整数字段的总和。我已经阅读了很多关于这方面的问题,在模板呈现之前,我似乎必须在视图中完成这项工作。然而,这意味着我必须分别定义每个类别的总数,而我希望重组可以避免这个麻烦。有没有其他更好的方法 {% regroup shops|dictsort:"category" by category as category_list %} {% for clist in category_list %}
{% regroup shops|dictsort:"category" by category as category_list %}
{% for clist in category_list %}
# here should come the total per category
{% endfor %}
我想这会回答你的问题。标题有点让人困惑,但我想你可以从中得到一些东西。我想这会回答你的问题。标题有点混乱,但我认为您可以从中获得一些信息。您可以在模型中创建函数,然后在模板中调用它
Category(models.Model)
........
def total(self):
qs = Category.objects.filter(id=self).aggregate(Sum('amount'))
sum = qs['amount__sum']
if not sum:
sum = 0.00
return sum
{% regroup shops|dictsort:"category" by category as category_list %}
{% for clist in category_list %}
{{clist}} - {{clist.total}}
{% endfor %}
您可以在模型中创建函数,然后在模板中调用它
Category(models.Model)
........
def total(self):
qs = Category.objects.filter(id=self).aggregate(Sum('amount'))
sum = qs['amount__sum']
if not sum:
sum = 0.00
return sum
{% regroup shops|dictsort:"category" by category as category_list %}
{% for clist in category_list %}
{{clist}} - {{clist.total}}
{% endfor %}
很抱歉延迟回复。有点失去了对这件事的关注。非常感谢您的投入!很抱歉延迟回复。有点失去了对这件事的关注。非常感谢您的投入!