[Answered ]-Cumulative count in recoursetree?

2👍

Found a function for this on the TreeManager:

https://github.com/django-mptt/django-mptt/blob/master/mptt/managers.py#L250

Add the counts to the queryset in your view:

context['qs_with_related_count'] = model1.objects.add_related_count(
                                          obj.get_children(),
                                          model2, 
                                          'category',
                                          'o_count',
                                          True
                                   )

and in template:

{% recursetree qs_with_related_count %}
    <li>
        <h2><a href="{{ node.get_absolute_url }}">{{ node }} ({{ node.o_count }})</a></h2>
        {% if not node.is_leaf_node %}
           <ul class="children">
               {{ children }}
           </ul>
        {% endif %}
    </li>
 {% endrecursetree %}

Unfortunately I was trying to use a ManyToManyField as rel_field:

https://github.com/django-mptt/django-mptt/issues/90

but it looks like you are in luck (‘category’ not ‘categories’) 🙂

👤sunn0

Leave a comment