sqlalchemy:具有不同连接类型的多个连接,并指定要加入的关系

时间:2015-06-23 22:17:26

标签: python sqlalchemy

我尝试进行多连接,其中每个后续表连接到join()属性上内部relationship()的先前连接的表,但我想要outerjoin()表4

查询如下:

self.s.query(Table1, Table2, Table3, Table4) \
      .join('relationship2', 'relationship3') \
      .outerjoin('relationship4') \
      .all()

最终发生的事情是Table4尝试加入Table1,而不是根据需要加入Table3.relationship4,产生InvalidRequestError:

InvalidRequestError: Entity '<class 'Table1'>' has no property 'relationship4'

如何指定outerjoin()使用表3中的自然外键关系?

1 个答案:

答案 0 :(得分:0)

所以事实证明,如果直接指定更强大的模型类,而不是尝试加入relationship()属性名称,则非常简单。我相信这只有在两个表之间存在一个外键关系时才有效。 SQLA join docs here.

例如,这将产生我正在寻找的东西,Table4显示为None,其中没有匹配的行:

self.s.query(Table1, Table2, Table3, Table4) \
  .join('relationship2', 'relationship3') \
  .outerjoin(Table4) \ # reference the model class directly here
  .all()