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.
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.
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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With