SQLAlchemy:在连接查询中使用 delete/update

SQLAlchemy: Using delete/update with a join query

使用 Flask-SQLAlchemy,我想根据链接到 table [=14] 的另一个 table 的值删除 table Questions 中的行=] 然后用外键链接到 table Subject。我试过这个查询:

db.session.query(Questions).join(Topic)join(Subject).filter(Subject.account_id==current_user.id).delete()

但是,我收到一个错误:

InvalidRequestError: Can't call Query.update() or Query.delete() when join(), outerjoin(), select_from(), or from_self() has been called

因此我想我不能将 .delete().join()

一起使用

这个问题有解决方法吗?谢谢。

您不必为您的查询使用连接,您可以像

那样以某种方式完成它
db.session.query(Post).filter(Post.user_id==current_user.id).delete()

假设您的 Post 有一个 user_id 列。

Join tables 不知道要删除哪个table,Post or User,因为它实际上有一个复杂的中间table构造,并从中查询.

根据 中的类似讨论,如果您使用的是 ORM 而不是 Core,我能够找出解决方法。将连接分解为单独的 cte/subquery,其中 return 您要更新的行的 ID。

question_joins = db.session.query(Question).join(Topic)join(Subject)
question_filter  = question_joins.filter(Subject.account_id==current_user.id)
question_id_subquery = question_filter.with_entities(Question.id).subquery()

db.session.query(Question).filter(Question.id.in_(question_id_subquery)).delete()