【问题标题】:SQLAlchemy Reference Column Through Foreign KeySQLAlchemy 通过外键引用列
【发布时间】:2019-07-02 02:49:45
【问题描述】:

如果我有一个operator 表和一个user 表,并且我与operator 中的user 表有多个关系,其中pm 是一个relationship(),它连接到operator.pm_id == user.idsales 是连接operator.sales_id == user.idrelationship(),如何在select 语句中从user 表中引用username 列,类似于以下内容:

stmt = select([operator, operator.pm.username.label('pm'), operator.sales.username.label('sales')])

这显然行不通,但我怎样才能完成类似的事情呢?

【问题讨论】:

  • 对不起,我不明白你想在这里完成什么。是否要执行联接操作?一个集合体?你能用简单的英语描述查询的期望结果吗?
  • 如果我说 select([operator]),我会得到基本的运算符列和 2 个 id:pm_id 和 sales_id。我想做的就是从用户表中返回这 2 个 id 的用户名,而不是整数 id。代替operator.name ... | operator.pm_id | operator.sales_id,返回operator.name ... | operator.pm(username from user table) | operator.sales(different username from user table)

标签: python sqlalchemy relationship


【解决方案1】:

核心思想是这样的:

stmt = select([operator.name, user.name])
stmt = stmt.select_from(operator.join(user, operator.pm_id==user.id))

您可以通过这种方式使用 select_from 语句从多个表中生成列的连接。

最后要添加的部分

operator.sales(与用户表不同的用户名)

我还没有完全理解。但也许你也可以使用上面的方案来解决这个问题。

编辑:

明确说明:您可以无限期地链接此操作,例如

stmt = stmt.select_from(table1.join(table2, table1.key==table2.key).join(table3, table2.key==table3.key))

等等。

【讨论】:

  • operatoruseruser.id 上只有一个关系时,这很有效,但是当我想要来自userusername 属性时,我很困惑该怎么做同时为下午和销售代表。
  • 在我的编辑中,我提到了如何将方案扩展到多个连接。只需将其应用于您的使用模式即可。
猜你喜欢
  • 2021-07-02
  • 2011-07-05
  • 2015-10-02
  • 2015-02-17
  • 1970-01-01
  • 2013-07-16
  • 1970-01-01
  • 2021-05-02
  • 1970-01-01
相关资源
最近更新 更多