I'm spitting out my categories tree like so:
<div id="categories-tree">
{% load mptt_tags %}
{% full_tree_for_model bugs.Category as cats cumalative count bugs.Bug.categories %}
{% for node, structure in cats|tree_info %}
{% if structure.new_level %}<ul><li>{% else %}</li><li>{% endif %}
<a href="/categories/{开发者_如何学运维{node.slug}}">{{ node }}</a>
{% for level in structure.closed_levels %}</li></ul>{% endfor %}
{% endfor %}
</div>
However, I want to also generate a <span class="count">13</span>
for my inner categories ( starting with the 3rd level maybe? ) of the amount of Bugs associated per category, as my bugs can have multiple categories associated.
I'm thinking I need something like this snippet inside my nested for loop but I'm not quite sure how to do it:
{% drilldown_tree_for_node [node] as [varname] count [foreign_key] in [count_attr] %}
Here's are my models for reference:
class Bug( models.Model ):
name = models.CharField( max_length=100 )
slug = models.SlugField(unique=True)
summary = models.TextField()
date_added = models.DateTimeField()
poster = models.ForeignKey(User)
categories = models.ManyToManyField('Category')
class Category ( models.Model ):
name = models.CharField( max_length=100 )
parent = models.ForeignKey('self', null=True, blank=True, related_name='children')
slug = models.SlugField(unique=True)
mptt.register(Category)
So the current out is:
<ul>
<li><a href="#">CSS</a>
<ul>
<li><a href="#">Position</a>
<ul>
<li><a href="#">Absolute</a></li>
<li><a href="#">Absolute Fixed</a></li>
</ul>
</li>
</ul>
</li>
</ul>
And ideal:
<ul>
<li><a href="#">CSS</a>
<ul>
<li><a href="#">Position</a>
<ul>
<li><a href="#">Absolute</a> <span>13</span></li>
<li><a href="#">Absolute Fixed</a> <span>10</span></li>
</ul>
</li>
</ul>
</li>
</ul>
Start off by adding a method to the category model:
def get_bug_count(self):
return Bugs.objects.filter(category=self).count()
And then in the template, in theory you should be able to do:
<span>{{ node.get_bug_count }}</span>
精彩评论