Created
February 25, 2018 01:57
-
-
Save mazz/59c696efc01af5164d666d1257b02c98 to your computer and use it in GitHub Desktop.
sqlalchemy many-to-many query examples
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## every leader at every church -- OK | |
## | |
## | |
## query = dbsession.query(Leader).join(LeaderChurch).join(Church).filter(LeaderChurch.leader_id == Leader.id and LeaderChurch.church_id == Church.id) | |
## every leader at a particular church -- OK | |
## | |
## | |
# query = dbsession.query(Leader). \ | |
# join(LeaderChurch). \ | |
# join(Church, Church.id == LeaderChurch.church_id). \ | |
# filter(Church.uuid == church_uuid.hex) | |
## works but associates sermons with the wrong church | |
## I think because there is a m-2-m church-leader via | |
## the LeaderChurch association table | |
query = dbsession.query(MediaSermon, Church). \ | |
join(Leader, Leader.id == MediaSermon.leader_id). \ | |
join(LeaderChurch, LeaderChurch.leader_id == Leader.id). \ | |
join(Church, Church.id == LeaderChurch.church_id). \ | |
filter(Church.uuid == church_uuid.hex). \ | |
order_by(MediaSermon.track_number.asc(), MediaSermon.id) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://stackoverflow.com/questions/19841877/an-inner-join-with-sqlalchemy