recursion - Iterate through Python Flask/Jinja2 adjacency list -
recursion - Iterate through Python Flask/Jinja2 adjacency list -
i'm trying print out list of nested comments using jinja2 recursive loop. problem have after printing out total nested branch, starts 1 time again 1 of nested children , draws list there.
i find way skip iteration if printed before.
i have next flask model defined:
class comment(db.model): """class containing comments 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
this loads few nested comments:
comment = comment(body="first comment") db.session.add(comment) db.session.commit() comment2 = comment(body="nested first comment", parent_id=comment.id) db.session.add(comment2) db.session.commit() comment3 = comment(body="also nested first comment", parent_id=comment.id) comment4 = comment(body="nested fist nested comment", parent_id=comment2.id) db.session.add(comment3) db.session.add(comment4) db.session.commit()
here's relevant jinja2 template:
<div class="row"> <ul class="media-list"> <li class="media"> {%- 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 kid --> {% endif %} </div> </div> {% endfor %} </li> </ul> </div>
it sounds initial query looks like
comments = comment.query.all() # perhaps there's order_by
this returns query set of comments in it, children. want comments aren't children of other comments.
comments = comment.query.filter(comment.parent_id == none) # same order_by goes here
python recursion flask jinja2 adjacency-list
Comments
Post a Comment