Django的总数

时间:2013-06-16 06:25:31

标签: django count django-templates

我有模特,观点& Django中的模板,并希望显示类别的总数。

class Entry (models.Model):
    title = models.CharField(max_length=200)
    category = models.ForeignKey('entry.Category')

class Category(models.Model):
    title = models.CharField(max_length=100)
    parent = models.ForeignKey('self', blank=True, null=True, related_name='children')

def category(request):
    category = Category.objects.all()
    return render_to_response('category.html', locals(), context_instance=RequestContext(request))

<ul>
{% for category in category %}
<li><a href="{{ category.slug }}">{{ category.title }}</a> ({{ category.entry_set.all.count }})</li>
{% endfor %}
</ul>

当前输出:

- 类别1(0)

- 子类别1(3)

- 子类别2(6)

欲望输出是这样的:

- 类别1(9)

- 子类别1(3)

- 子类别2(6)

如何获得该输出?

2 个答案:

答案 0 :(得分:2)

使用category.entry_set.count代替category.entry_set.all.count

此外,您使用相同的变量名category来引用多个值,您可能想要更改它。

将模板更新为:

<ul>
{% for cat in category %}
<li><a href="{{ cat.slug }}">{{ cat.title }}</a> ({{ cat.entry_set.count }})</li>
{% endfor %}
</ul>

答案 1 :(得分:0)

使用Django-MPTT解决并更新我的视图&amp;像这样的模板:

views.py:

def category(request):
    category = Category.tree.add_related_count(Category.objects.all(), Entry, 'category', 'cat_count', cumulative=True)
    return render_to_response('category.html', locals(), context_instance=RequestContext(request))

category.html:

{% recursetree category %}
<ul>
<a href="{{ node.slug }}">{{ node.title }} ({{ node.cat_count }})</a>
{% if not node.is_leaf_node %}
<li class="children">
{{ children }}
</li>
{% endif %}
</ul>
{% endrecursetree %}
相关问题