Django 资源树中的累积计数?

Django 资源树中的累积计数?,django,django-mptt,Django,Django Mptt,使用我想浏览我的类别层次结构,显示与当前类别的任何子类别相关的对象数量 与所示示例非常相似,但仅适用于当前节点子节点 最佳方案是 {% recursetree obj.get_children cumulative count model.Foreignkey.category in o_count%} <li> <h2><a href="{{ node.get_absolute_url }}">{{ node }}</a></h2&

使用我想浏览我的类别层次结构,显示与当前类别的任何子类别相关的对象数量

与所示示例非常相似,但仅适用于当前节点子节点

最佳方案是

{% recursetree obj.get_children cumulative count model.Foreignkey.category in o_count%}
<li>
    <h2><a href="{{ node.get_absolute_url }}">{{ node }}</a></h2>
    {% if not node.is_leaf_node %}
    <ul class="children">
        <a href="{{ children.get_absolute_url }}">{{ children }} ({{o_count}})</a>
    </ul>
    {% endif %}
</li>
{% endrecursetree %}
{%recursetree obj.get_children累积计数model.Foreignkey.category in o_count%}
  • {%如果不是node.is_leaf_node%}
    {%endif%}
  • {%endrecursetree%}

    有任何指针吗?

    在TreeManager上找到用于此的函数:

    将计数添加到视图中的查询集:

    context['qs_with_related_count'] = model1.objects.add_related_count(
                                              obj.get_children(),
                                              model2, 
                                              'category',
                                              'o_count',
                                              True
                                       )
    
    在模板中:

    {% 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 %}
    
    {%recursetree qs_与_相关_计数%}
    
  • {%如果不是node.is_leaf_node%}
      {{儿童}
    {%endif%}
  • {%endrecursetree%}
    不幸的是,我试图将
    ManyToManyField
    用作
    rel\u字段


    但是看起来你很幸运(“类别”而不是“类别”):

    没有迭代
    get_children
    并在每个孩子身上调用模板标记来帮助你吗?我想要一个与孩子相关的对象的累积计数,就像“所有子类别中的总和项”…你找到解决方案了吗?@sunn0,还没有。请将问题暂时置于备用状态。下周将给它一个新的机会…看也没有时间尝试这个。但这可能是正确的。我会接受这个答案,因为没有新的答案。非常感谢你!