【发布时间】:2026-01-19 13:50:01
【问题描述】:
所以,我正在开发一个小型博客风格的网络应用程序作为个人项目。我现在已经可以正常工作了,但是我在尝试在帖子上实现 cmets 时遇到了麻烦。
我设置帖子的方式是通过 SQLAlchemy ORM 模型,该模型运行良好。它具有内容和标题字段以及其他字段,以及与帖子作者的多对一关系,例如:
class Post(db.Model):
id = db.Column(db.Integer, primary_key = True)
title = db.Column(db.String(100), nullable=False)
date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
content = db.Column(db.Text, nullable=False)
feature_image = db.Column(db.String, nullable=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
comments = db.relationship('Comment', backref='original_post', lazy=True)
我的 cmets 遵循相同的结构,与帖子具有多对一的关系,如下所示:
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)
post_id = db.Column(db.Integer, db.ForeignKey('post.id'), nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
因此,为了让 cmets 显示在帖子下方,我尝试从“post”表中查询“comment”表并过滤“post_id”,它应该与 post.id 匹配:
@app.route('/post/<int:post_id>')
def post(post_id):
post = Post.query.get_or_404(post_id)
comments = Comment.query.filter(Comment.original_post==post)
但是当我尝试加载帖子页面时,它会抛出以下错误:
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such column: comment.post_id
[SQL: SELECT comment.id AS comment_id, comment.date_posted AS comment_date_posted, comment.content AS comment_content, comment.post_id AS comment_post_id, comment.user_id AS comment_user_id
FROM comment
WHERE ? = comment.post_id]
[parameters: (1,)]
(Background on this error at: http://sqlalche.me/e/e3q8)
我查看了有关该主题的其他一些线程,这些线程建议在查询之前使用 .join,如下所示:
comments = Comment.query.join(Post).filter(Post.id == post_id).all()
但我得到一个类似的错误:
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such column: comment.post_id
[SQL: SELECT comment.id AS comment_id, comment.date_posted AS comment_date_posted, comment.content AS comment_content, comment.post_id AS comment_post_id, comment.user_id AS comment_user_id
FROM comment JOIN post ON post.id = comment.post_id
WHERE post.id = ?]
[parameters: (1,)]
【问题讨论】:
-
您能否(直接)检查您的数据库,无论您的
comment表中是否有post_id列。 -
@oli 是的,就是这样。就在我头上,非常感谢你
标签: python flask sqlalchemy flask-sqlalchemy