{% ...">

Including the number of foreign keys in django mptt complete list of trees?

I spit out my category tree like this:

<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 also want to generate <span class="count">13</span> for my internal categories (starting at level 3, maybe?) From the number of errors associated with each category, as my errors may have several related categories.

I think I need something like this snippet inside my nested loop, but I'm not quite sure how to do this:

  {% drilldown_tree_for_node [node] as [varname] count [foreign_key] in [count_attr] %} 

Here 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 output 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 the 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> 
+3
django django-mptt
source share
1 answer

Start 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, theoretically, you can do this:

 <span>{{ node.get_bug_count }}</span> 
+1
source share

All Articles