【问题标题】:Hi I'm trying to write a sql alchemy query but it gives me the error "cant determine which from clause to join from"嗨,我正在尝试编写一个 sql alchemy 查询,但它给了我错误“无法确定要从哪个 from 子句加入”
【发布时间】:2021-02-16 19:27:54
【问题描述】:

所以我有一个连接表并获取数据的 sql 查询

select "FileSets"."Id", "SetFile"."Alias" from "Feeds"
join "FeedSnapshots" on "Feeds"."ActiveSnapshotId"="FeedSnapshots"."Id"
join "Subscriptions" on "Feeds"."Id" = "Subscriptions"."FeedId"
join "SubscriptionSnapshots" on "Subscriptions"."ActiveSnapshotId"="SubscriptionSnapshots"."Id"
join "FileSets" on "SubscriptionSnapshots"."Id"="FileSets"."SubscriptionSnapshotId"
join "SetFile" on "FileSets"."Id"="SetFile"."FileSetId" where "Feeds"."Id"=398 and "Expected"=true

现在我正在尝试将其转换为 sqlAlchemy 查询,但它给了我以下错误:

sqlalchemy.exc.InvalidRequestError: Can't determine which FROM clause to join from, there are multiple FROMS which can join to this entity. Please use the .select_from() method to establish an explicit left side, as well as providing an explcit ON clause if not present already to help resolve the ambiguity.

我的 sqlAlchemy 查询如下所示:

db.session.query(FileSet.id, SetFile.alias).join(FeedSnapshot, Feed.active_snapshot_id == FeedSnapshot.id) \
        .join(Subscription, Feed.id == Subscription.feed_id).join(SubscriptionSnapshot, Subscription.active_snapshot_id == SubscriptionSnapshot.id) \
        .join(FileSet, SubscriptionSnapshot.id == FileSet.subscription_snapshot_id).join(SetFile, FileSet.id == SetFile.file_set_id) \
        .filter(and_(SetFile.expected, Feed.id == orig_feed_snapshot.feed_id)).all()

谁能告诉我我在 SqlAlchemy 查询中做错了什么?

【问题讨论】:

  • 我认为你可以使用select_from(table)
  • 谢谢,成功了
  • 我喜欢这样。我建议您也测试其他变体。随着应用程序开发的继续,它可能会更有帮助。

标签: python postgresql flask sqlalchemy


【解决方案1】:

根据你是否愿意,你也可以用flask_sqlalchemy代替纯sqlalchemy请求。

以下查询应该可以工作。

id_alias_pairs = Feed.query\
  .join(FeedSnapshot, Feed.active_snapshot_id == FeedSnapshot.id)\
  .join(Subscription, Feed.id == Subscription.feed_id)\
  .join(SubscriptionSnapshot, Subscription.active_snapshot_id == SubscriptionSnapshot.id)\
  .join(FileSet, SubscriptionSnapshot.id == FileSet.subscription_snapshot_id)\
  .join(SetFile, FileSet.id == SetFile.file_set_id)\
  .filter(Feed.id==1, SetFile.expected)\
  .with_entities(FileSet.id, SetFile.alias)\
  .all()

print(id_alias_pairs)

【讨论】:

    猜你喜欢
    • 2021-02-04
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 2019-03-09
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 2020-09-02
    相关资源
    最近更新 更多