Reputation: 236
I have models, views & template in Django and want to display the total count of category.
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>
Current output:
-Category 1 (0)
--Sub Category 1 (3)
--Sub Category 2 (6)
And desire output is like this:
-Category 1 (9)
--Sub Category 1 (3)
--Sub Category 2 (6)
How to get that output?
Upvotes: 0
Views: 817
Reputation: 236
Solved by using Django-MPTT and update my view & template like this:
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 %}
Upvotes: 0
Reputation: 53326
Use category.entry_set.count
instead of category.entry_set.all.count
.
Also, you are using same variable name category
for referencing multiple values, you may want to change that.
Update template as:
<ul>
{% for cat in category %}
<li><a href="{{ cat.slug }}">{{ cat.title }}</a> ({{ cat.entry_set.count }})</li>
{% endfor %}
</ul>
Upvotes: 2