【问题标题】:Iterate through Python Flask/Jinja2 adjacency list遍历 Python Flask/Jinja2 邻接表
【发布时间】:2014-10-07 09:32:12
【问题描述】:

我正在尝试使用 Jinja2 递归 for 循环打印出嵌套 cmets 列表。我遇到的问题是,在打印出一个完整的嵌套分支后,它又从一个嵌套的子分支开始,并从那里绘制另一个列表。

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

我定义了以下 Flask 模型:

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

这会加载一些嵌套的 cmets:

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>

【问题讨论】:

    标签: python recursion flask jinja2 adjacency-list


    【解决方案1】:

    听起来您的初始查询类似于

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

    这将返回一个包含所有 cmets 的查询集,即使是那些子项。您真正想要的只是那些不是其他 cmets 的子代的 cmets。

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

    【讨论】:

      猜你喜欢
      • 2014-01-27
      • 1970-01-01
      • 2019-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-19
      相关资源
      最近更新 更多