如何在同一页面查询一对多

How to query one to many on same page

我有2个表,它们各自的关系,一个post可以有很多评论。

我现在问我的看法

posts = Post.query.all()

如何使用 ORM 从 post 的单个查询中提取所有评论?


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

我想做这样的事情,但不可能

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

{% endfor %}

您可以简单地在 'post' table 中使用 'comments' 关系。这意味着 post.comments returns 的所有 post 评论的列表。您的 Jinja 循环可能看起来像这样:

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