Including foreign key count in django mptt full tree listing?

这一生的挚爱 提交于 2019-12-01 08:38:50

问题


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>

回答1:


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>


来源:https://stackoverflow.com/questions/3224837/including-foreign-key-count-in-django-mptt-full-tree-listing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!