亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Flask+SQLAlchemy 在嘗試按外鍵列過濾記錄時拋出 OperationalError

Flask+SQLAlchemy 在嘗試按外鍵列過濾記錄時拋出 OperationalError

qq_遁去的一_1 2023-06-13 10:53:26
因此,作為個人項目,我正在開發一個小型博客風格的 Web 應用程序。我現在已經基本可以正常工作了,但是我在嘗試對帖子發表評論時遇到了麻煩。我設置帖子的方式是通過 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)我的評論遵循相同的結構,與帖子具有多對一的關系,如下所示: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)因此,為了讓評論顯示在帖子下方,我試圖查詢“評論”表并從“帖子”表中過濾“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()
查看完整描述

1 回答

?
狐的傳說

TA貢獻1804條經驗 獲得超3個贊

在 db 文件中的“評論”表只是缺少外鍵字段。



查看完整回答
反對 回復 2023-06-13
  • 1 回答
  • 0 關注
  • 143 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號