【问题标题】:Django mptt recursetree with get_cached_trees in template模板中带有 get_cached_trees 的 Django mptt 递归树
【发布时间】:2020-02-18 20:21:22
【问题描述】:

在视图中:

context['categories'] =  = models.Category.objects.all().get_cached_trees()

在模板中:

{% load mptt_tags %}
<ul>
    {% recursetree categories %}
        <li>
            {{ node.name }}
            {% if not node.is_leaf_node %}
                <ul class="children">
                    {{ children }}
                </ul>
            {% endif %}
        </li>
    {% endrecursetree %}
</ul>

因此,它只呈现第一级查询集。如果删除 get_cached_trees 它会呈现所有树。如何用get_cached_trees渲染所有树?

【问题讨论】:

    标签: python django django-mptt


    【解决方案1】:

    在这种情况下,您实际上不需要调用 get_cached_trees(),因为 recursettree 已经为您完成了缓存。

    来自文档:

    Iterates over the nodes in the tree, and renders the contained block for each node.
    This tag will recursively render children into the template variable {{ children }}.
    Only one database query is required (children are cached for the whole tree)
    

    【讨论】:

      最近更新 更多