Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Outer Join with ORM mapping in SQLAlchemy

I am using the ORM Mapping in SQLAlchemy 0.6.8.

I have three tables (A, B and C), with no foreign keys between them.

I am trying to join table A and B, and then left outer join that with C. I am expecting a named tuple, with fields A, B and C - with the C field sometimes set to None.)

I can do the first join easily enough by just selecting both table.

(session.query(A, B)
    .filter(A.some_field = B.some_other_field))

That gets me a NamedTuple with fields A and B.

I then add the outer join, to make it:

(session.query(A, B)
    .filter(A.some_field==B.some_other_field))
    .outerjoin((C, A.some_field==C.some_different_field))

The result still only has two tables. I can't access the other fields of C (even in the cases where they are present).

What is the correct way to do an left outer join, to get access to the fields of the right-most table??

I'd rather not fallback to the basic SQL if I could avoid it - I am trying to learn to take advantage of the ORM.

like image 570
Oddthinking Avatar asked Jun 05 '11 01:06

Oddthinking


People also ask

What is outer join in SQLAlchemy?

Python Flask and SQLAlchemy ORM Effect of joining is achieved by just placing two tables in either the columns clause or the where clause of the select() construct. Now we use the join() and outerjoin() methods. The join() method returns a join object from one table object to another.

What is ORM SQLAlchemy?

SQLAlchemy is a library that facilitates the communication between Python programs and databases. Most of the times, this library is used as an Object Relational Mapper (ORM) tool that translates Python classes to tables on relational databases and automatically converts function calls to SQL statements.


1 Answers

This should work:

(session.query(A)
    .join(B, A.some_field == B.some_other_field)
    .outerjoin(C, A.some_field == C.some_different_field)
    .add_entity(B)
    .add_entity(C))
like image 200
sayap Avatar answered Oct 04 '22 20:10

sayap