我正在使用django-mttp.如何限制 recursetree 的最大深度?最多= 3
I'm using django-mttp. How can I limit the max depth of recursetree? Max=3
型号:
class Comment(MPTTModel): """评论表""" nid = models.AutoField(primary_key=True) news = models.ForeignKey( verbose_name="评论文章", to="News", to_field="id", on_delete=models.CASCADE, ) user = models.ForeignKey( verbose_name="评论者", to="User", to_field="id", on_delete=models.CASCADE, ) content = models.CharField(verbose_name="评论内容", max_length=255) create_time = models.DateTimeField(verbose_name="创建时间", auto_now_add=True) parent = TreeForeignKey( "self", on_delete=models.CASCADE, null=True, blank=True, related_name="children", ) class MPTTMeta: order_insertion_by = ["create_time"]模板:
<ul> {% recursetree comments_list %} <li> {{ node.content }} {{ node.level }} {% if node.parent %} <div>{{node.user}} 回复 {{node.parent.user}}</div> {% endif %} <button class="button" onclick="myFunction({{node.id}})"> Reply </button> {% if not node.is_leaf_node %} <ul class="children list-item"> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} </ul> 推荐答案MPTTModel 的每个实例都有一个 level 属性,该属性可用于将递归深度限制为.只需编辑递归模板即可不显示超过特定深度的水平:
Every instance of MPTTModel has a level attribute that can be used to limit the depth to recurse to. Just edit the recursive template to not show levels above a certain depth:
<ul> {% with max_depth=3 %} {% recursetree comments_list %} <li> {% if not node.is_leaf_node and node.level < max_depth %} <ul>{{ children }}</ul> {% endif %} </li> {% endrecursetree %} {% endwith %} </ul>