SqlAlchemy连接没有外键的表

时间:2015-01-12 18:25:07

标签: python sql sqlalchemy

我在SqlAlchemy中有两个表

class T1(Record, SqlBase):
    __tablename__ = 'table1'
    __table_args__ = (PrimaryKeyConstraint('column'), {'autoload': True},)

class T2(Record, SqlBase):
    __tablename__ = 'table2'
    __table_args__ = (PrimaryKeyConstraint('column'), {'autoload': True},)

我想在一些常见的列

上加入这两个表
session.query(T1).join(session.query(T2), T1.column == T2.column)

但我收到了错误

InvalidRequestError: Could not find a FROM clause to join from.  Tried joining to 
... but got: Can't find any foreign key relationships 
between 'T1' and 'FromGrouping object'. Perhaps you
 meant to convert the right side to a subquery using alias()?

如何解决此问题?两个表中都没有外键

1 个答案:

答案 0 :(得分:2)

有用的Doc

如果两个类都有关系,你可以使用join,或者你可以编写没有像这样的连接的查询

session.query(T1).filter(T1.column == T2.column)