Home > Back-end >  How to query one to many on same page
How to query one to many on same page

Time:05-12

I have 2 tables with their respective relationships, a post can have many comments.

I currently ask on my view

posts = Post.query.all()

How would I pull all the comments from a post on a single query using ORM?


class Post(db.Model):
    __tablename__ = 'posts'
    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.String(255))
    created_on = db.Column(db.DateTime, index=True, default=datetime.datetime.utcnow)    
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))    
    user_name = db.Column(db.String(64))
    comments = db.relationship('Comment', backref='comment', lazy='dynamic')
    likes = db.relationship('PostLike', backref='post', lazy='dynamic')

    def __repr__(self):
        return '<Post \'%s\'>' % self.id





class Comment(db.Model):
    __tablename__ = 'comments'
    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.String(255))
    created_on = db.Column(db.DateTime, index=True, default=datetime.datetime.utcnow)
    likes = db.Column(db.Integer)
    user_name = db.Column(db.String(64)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    post_id = db.Column(db.Integer, db.ForeignKey('posts.id'))

    def __repr__(self):
        return '<Comment \'%s\'>' % self.id

I would like to do something like this but it's not possible

{% for post in posts %}
<p>{{post.content}}</p>
<ul>
   {% for comments in post %}
   <li>{{post.comments}}</li>
   {% endfor %}

{% endfor %}

CodePudding user response:

You can simply make use of the 'comments' relationship in your 'post' table. This means that post.comments returns a list of all that post's comments. Your Jinja loop could look something like this:

{% for comment in post.comments %}
    <li>{{comment}}</li>
{% endfor %}
  • Related