Created
March 16, 2012 11:43
-
-
Save dnouri/2049711 to your computer and use it in GitHub Desktop.
Query node children with arbitrary depth
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
def query_children(context, levels=3, more_conditions=None): | |
selects = [] | |
for level in range(levels): | |
alias = Node.__table__ | |
conditions = [Node.__table__.c.id == context.id] | |
for depth in range(level + 1): | |
alias, old_alias = Node.__table__.alias(), alias | |
conditions.append(alias.c.parent_id == old_alias.c.id) | |
if more_conditions: | |
for key, value in more_conditions.items(): | |
conditions.append(getattr(alias.c, key) == value) | |
selects.append(select([alias.c.id], and_(*conditions))) | |
sel_union = selects.pop(0).alias().select() | |
for sel in selects: | |
sel_union = sel_union.union(sel).alias().select() | |
return DBSession.query(Node).filter(Node.id.in_(sel_union)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment