在django mptt完整树列表中包括外键计数?

时间:2010-07-11 22:20:21

标签: django django-mptt

我正在吐出我的类别树:

<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>

但是,我还要为我的内部类别(从第3级开始,可能是?)生成<span class="count">13</span>每个类别相关的错误数量,因为我的错误可能有多个类别关联。

我想我的嵌套for循环中需要这样的代码片段,但我不太清楚该怎么做:

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

以下是我的模型供参考:

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)

所以目前的情况是:

<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>

理想:

<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 个答案:

答案 0 :(得分:1)

首先向类别模型添加方法:

def get_bug_count(self):
    return Bugs.objects.filter(category=self).count()

然后在模板中,理论上你应该能够做到:

<span>{{ node.get_bug_count }}</span>