2014-10-07 42 views
0

我想使用Jinja2递归for循环打印出嵌套注释列表。我遇到的问题是在打印出一个完整的嵌套分支后,它会从一个嵌套的子节点重新开始并从那里绘制另一个列表。迭代通过Python Flask/Jinja2邻接列表

我想找到一种方法来跳过迭代,如果它已经打印过。

我有以下瓶模型中定义:

class Comment(db.Model): 
    """Class containing comments to a post""" 

    __tablename__ = "comment" 

    id = db.Column(db.Integer, primary_key=True) 
    body = db.Column(db.String(255)) 

    parent_id = db.Column(db.Integer, db.ForeignKey('comment.id')) 
    children = db.relationship("Comment") 

    def __init__(self, body=None, parent_id=None): 
     self.body = body 
     self.parent_id = parent_id 

这将加载了几个嵌套的注释:

comment = Comment(body="First Comment") 
db.session.add(comment) 
db.session.commit() 

comment2 = Comment(body="Nested with First Comment", parent_id=comment.id) 

db.session.add(comment2) 
db.session.commit() 

comment3 = Comment(body="Also nested with First Comment", parent_id=comment.id) 
comment4 = Comment(body="Nested with the fist nested comment", parent_id=comment2.id) 

db.session.add(comment3) 
db.session.add(comment4) 
db.session.commit() 

下面是相关的Jinja2模板:

<div class="row"> 
    <ul class="media-list"> 
    <li class="media"> 
     {%- for comment in user.musician.comments recursive %} 
     <div class="media"> 
     <span class="pull-left"> 
          {{ comment.author.name }} said: 
         </span> 
     <div class="media-body"> 
      <p>{{comment.body }}</p> 
      {% if comment.children %} 
      <!-- Children starts here --> 
      {{ loop(comment.children) }} 
      <!-- end of child --> 
      {% endif %} 
     </div> 
     </div> 
     {% endfor %} 
    </li> 
    </ul> 
</div> 

回答

0

这听起来像您的初始查询看起来像

comments = Comment.query.all() # perhaps there's an order_by 

这将返回一个包含所有注释的查询集,即使是那些儿童。你真正想要的只是那些不是其他评论的孩子的评论。

comments = Comment.query.filter(Comment.parent_id == None) # same order_by goes here 
+0

谢谢@dirn,那就是诀窍! – thiezn 2014-10-08 08:29:28