Skip to content

Instantly share code, notes, and snippets.

@makmanalp
Created September 11, 2017 18:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save makmanalp/1cfa45e1c8a1a5c6e545facf30b75c9e to your computer and use it in GitHub Desktop.
Save makmanalp/1cfa45e1c8a1a5c6e545facf30b75c9e to your computer and use it in GitHub Desktop.
Readable double self join / tree traversal in SQLAlchemy
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