python - 修复用户对帖子的评论功能——flask 应用程序

标签 python flask flask-sqlalchemy

我正在尝试链接我的用户、帖子和评论模型,以便在创建评论后,我希望能够列出该帖子的所有评论(带有作者信息)。

在我的 jinja2 模板中:

{% for post in posts %}
    {{ post.title }}
    {{ post.content }}
    {% for comment in post.comments %}
        {{ comment.author.email }} 
        {{ comment.author.username }}
        {{ comment.content }}
    {% endfor %}
{% endfor %}

但是,我无法正确链接模型。现在我有:

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique=True, nullable=False)
    ...

    posts = db.relationship('Post', backref='author', primaryjoin="User.id==Post.author_id")

    comments = db.relationship('Comment', backref='author', primaryjoin="User.id==Comment.author_id")

    def __repr__(self):
        return "{}, {}, {}".format(self.username, self.email)


class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    author_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    content = db.Column(db.Text, nullable=False)
    ...

    comments = db.relationship('Comment', backref='post', lazy=True)


    def __repr__(self):
        return "Post(Title:'{}', Content:'{}')".format(self.title, self.content)


class Comment(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    content = db.Column(db.Text, nullable=False)
    author_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    post_id = db.Column(db.Integer, db.ForeignKey('post.id'), nullable=False)

    def __repr__(self):
        return "Comment({})".format(self.content)

但是,这不起作用。在终端中尝试时,post.comments 返回“[ ]”(空列表)。总的来说,模特关系让我度过了一段艰难的时期。

****已编辑**** 这是我想要查询的方式之一的示例:

@app.route("/myposts", methods=['GET', 'POST'])
@login_required
def myposts():
    page = request.args.get('page', 1, type=int)
    user = User.query.filter_by(username=current_user.username).first_or_404()
    posts = Post.query.filter_by(author=user)\
            .order_by(Post.date_posted.desc())\
            .paginate(page=page, per_page=5)
    return render_template('myposts.html', title='My Posts', posts=posts, user=user)

最佳答案

获取所有信息的一种方法是稍微更改查询以使用显式查询:

posts = db.session.query(Post, User, Comments)\
            .join(User)\
            .join(Comments)\
            .filter(Post.author==user)\
            .order_by(Post.date_posted.desc())\
            .paginate(page=page, per_page=5)

这里我假设UserComment之间的关系不再存在。但是,即使是这样,您也可以通过以下方式调试关系并获得对查询的更多控制:

1)查看ORM生成的实际语句:

posts = db.session.query(Post, User, Comments)\
            .join(User)\
            .join(Comments)\
            .filter(Post.author==user)\
            .order_by(Post.date_posted.desc())

str(posts) # or posts.statement will print the query

2) 让您的查询更加明确:

posts = db.session.query(
                Post.id, Post.content, User.id, User.username, 
                Comments.date_posted, Comments.content.label('comm_content')
             )\
            .join(User)\ #you can even make this more explicit with .join(User, Post.author_id == User.id)
            .join(Comments)\ #same as above
            .filter(Post.author==user)\
            .order_by(Post.date_posted.desc())

关于python - 修复用户对帖子的评论功能——flask 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57281328/

相关文章:

python - 在 mongodb 中聚合时是否可以将 "_id"重命名为其他名称?

基于 Python Rate Limit 类的 View Flask

python - Flask-Admin 具有多对多关系中的附加字段

python - 我可以在没有事务的情况下通过 sqlalchemy 执行查询吗

python - 在 Python 3.7 中将字典追加到列表中

python - 如何在Python中不使用shutil将文件从一个位置复制到另一个位置

php - 将河豚加密算法从 php 转换为 python

python - 基于两个 numpy 数组和 matplotlib 创建的奇怪图

python - Flask 测试 - 为什么覆盖范围不包括导入语句和装饰器?

design-patterns - 异步图片上传模式