Created
September 11, 2017 18:46
-
-
Save makmanalp/1cfa45e1c8a1a5c6e545facf30b75c9e to your computer and use it in GitHub Desktop.
Readable double self join / tree traversal in SQLAlchemy
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
FourDigit = aliased(HSProduct) | |
TwoDigit = aliased(HSProduct) | |
Section = aliased(HSProduct) | |
product_data = db.session\ | |
.query( | |
FourDigit.id.label("product_id"), | |
FourDigit.code.label("product_code"), | |
FourDigit.name_en.label("product_name"), | |
Section.id.label("section_id"), | |
Section.code.label("section_code"), | |
Section.name_en.label("section_name"), | |
)\ | |
.join(TwoDigit, FourDigit.parent_id == TwoDigit.id)\ | |
.join(Section, TwoDigit.parent_id == Section.id)\ | |
.order_by(Section.name_short_en)\ | |
.all() | |
product_data = {x.product_id: x._asdict() for x in product_data} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment