使用MPTT在模板中执行get_children(在运行时)

时间:2013-04-06 16:32:49

标签: django django-mptt mptt

我的模板收到一个名为categories的变量,我想列出其父类别“儿子”的类别

这是我在模板中的代码

{% for category,structure in categories|tree_info %}
    {% if structure.new_level %}
<li><a href="/categories/{{ category.id }}/">{{ category.name }}</a> </li>   
    {% endif %}

    {% for level in structure.closed_levels %}
<li>{{level.name}}
    {% endfor %}

    <ul class="noJS">
    {% for cat in category.get_children|tree_info %}
    <li><a href="/categories/{{ cat.id }}/">{{  cat.name }}aa</a> </li> 

    {% endfor %}
    </ul>
{% endfor %}

这是模型

class Category(MPTTModel):
    name = models.CharField(max_length=50, unique=True)
    description = models.TextField(blank=True)
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children')

    class MPTTMeta:
        order_insertion_by = ['name']

    def __unicode__(self):
        return self.name

任何想法?

1 个答案:

答案 0 :(得分:0)

这有效

{% for category in categories %}
                <li>
                <a href="/categories/{{ category.id }}/">{{ category.name }}</a>  
                <ul class="noJS">
                    {% for cat in category.get_children %}              
                    <li><a href="/categories/{{ cat.id }}/">{{  cat.name }}</a> </li> 
                    {% endfor %}

                </ul>
            </li>
                {% endfor %}