Michael
Michael

Reputation: 7377

SqlAlchemy join on tables with no foreign keys

I have two tables in 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},)

I want to join the two tables on some common column

session.query(T1).join(session.query(T2), T1.column == T2.column)

But I'm getting an error

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()?

How do I fix this problem? There are no foreign keys in either table

Upvotes: 6

Views: 5420

Answers (1)

Anurag jain
Anurag jain

Reputation: 2451

Useful Doc

You can use join if both class having relationship or you can write query without join like this

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

Upvotes: 3

Related Questions