因此,作為個(gè)人項(xiàng)目,我正在開(kāi)發(fā)一個(gè)小型博客風(fēng)格的 Web 應(yīng)用程序。我現(xiàn)在已經(jīng)基本可以正常工作了,但是我在嘗試對(duì)帖子發(fā)表評(píng)論時(shí)遇到了麻煩。我設(shè)置帖子的方式是通過(guò) SQLAlchemy ORM 模型,效果很好。它有內(nèi)容和標(biāo)題字段等等,以及與帖子作者的多對(duì)一關(guān)系,如下所示: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)我的評(píng)論遵循相同的結(jié)構(gòu),與帖子具有多對(duì)一的關(guān)系,如下所示: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)因此,為了讓評(píng)論顯示在帖子下方,我試圖查詢“評(píng)論”表并從“帖子”表中過(guò)濾“post_id”,它應(yīng)該與 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)但是當(dāng)我嘗試加載帖子頁(yè)面時(shí),它會(huì)拋出以下錯(cuò)誤: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)我查看了有關(guān)該主題的其他一些主題,建議在查詢之前使用 .join ,如下所示:comments = Comment.query.join(Post).filter(Post.id == post_id).all()
添加回答
舉報(bào)
0/150
提交
取消