Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 559
Michael Avatar asked Jan 12 '15 18:01

Michael


People also ask

How do I join two tables in SQLAlchemy?

relationship() will normally create a join between two tables by examining the foreign key relationship between the two tables to determine which columns should be compared.

What is Backref in SQLAlchemy?

In Flask-SQLAlchemy, the backref parameter in relationship method allows you to declare a new property under a specified class as seen in the example in their docs: class Person(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50)) addresses = db.relationship('Address', backref='person ...

Can SQLAlchemy be used without Flask?

One of the most sought after helpers being the handling of a database connection across the app. However, ensuring your database connection session is available throughout your app can be accomplished with base SQLAlchemy and does not require Flask-SQLAlchemy.


1 Answers

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)
like image 94
Anurag jain Avatar answered Oct 17 '22 21:10

Anurag jain