0

I want to dynamically join a certain number of tables from a list containing table names, for example if my list contains two elements like this :

tables_to_join = ['table1','table2']

Then I would like to have a left join between those two tables in the query.

table1 LEFT JOIN table2 on table1.id = table2.id

And if the table only contains one element, then there will be no need to do a join.

How can I do this with SQLAlchemy please?

I guess I should do something like this :

test_query = session.query(my_table).join(tables_to_join)

But then how can I manage the case where there will be no need to join (if table_to_join contains only one element) ?

Any help would be awesome!

1
  • Can't you just check the length of the tables_to_join, and then stick the .join(tables_to_join) part in an if loop? Or did I miss something here. Commented Jul 4, 2013 at 12:04

1 Answer 1

1
tables_to_join = [..]

if (len(tables_to_join) > 1):
    query = session.query(eval(tables_to_join[0]))

    for table in tables_to_join[1:]:
        query = query.join(eval(table))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.