如何在 django-mptt 中显示一定数量的级别?
How to show a certain number of levels in django-mptt?
在我的 Django 项目中,我使用 django-mptt 应用程序来创建分层树。现在下一个代码运行良好,但我只想显示树的前 4 层。如何正确制作?我很困惑。
views.py:
context['caregories'] = Category.objects.get(id=5).get_descendants()
html:
{% load mptt_tags %}
<ul>
{% recursetree caregories %}
<li>
{{ node.name }}
{% if not node.is_leaf_node %}
<ul class="children">
{{ children }}
</ul>
{% endif %}
</li>
{% endrecursetree %}
</ul>
您可以按级别筛选后代
obj = Category.objects.get(id=5)
context['caregories'] = obj.get_descendants().filter(level__lte=obj.level + max_depth)
其中 max_depth
是您需要的深度
在我的 Django 项目中,我使用 django-mptt 应用程序来创建分层树。现在下一个代码运行良好,但我只想显示树的前 4 层。如何正确制作?我很困惑。
views.py:
context['caregories'] = Category.objects.get(id=5).get_descendants()
html:
{% load mptt_tags %}
<ul>
{% recursetree caregories %}
<li>
{{ node.name }}
{% if not node.is_leaf_node %}
<ul class="children">
{{ children }}
</ul>
{% endif %}
</li>
{% endrecursetree %}
</ul>
您可以按级别筛选后代
obj = Category.objects.get(id=5)
context['caregories'] = obj.get_descendants().filter(level__lte=obj.level + max_depth)
其中 max_depth
是您需要的深度