Question

I'm new to SQLAlchemy, after coming from Django ORM. I'm trying to create a simple nested set pattern & I would like to do parent lookup. Which I would do like this in Django ORM:

Page.objects.get(slug="currentlevel",parent__slug="secondlevel",parent__parent__slug="firstlevel")

This would automagically query the database for each parent item, returning the relevant page row.

In SQLAlchemy, the best I can come up with is:

session.query(Page).join(Page.parent, aliased=True).filter_by(slug="child")

So I can query the immediate parent item, but how can I continue up the chain in one query? Dynamically if possible (arbitrary amount of levels)

Please keep in mind I'm new to SQLAlchemy, and coming from the relatively sheltered Django ORM. I'm sure there's information in the SQLAchemy docs but I've read through it and can't seem to find it.

Thanks for your help.

Was it helpful?

Solution

You are right, all information in sqlalchemy docs under Self-Referential Query Strategies. In which case your initial query would look something like this:

from sqlalchemy.orm import aliased
page1 = aliased(Page)
page2 = aliased(Page)
qry = (session
        .query(Page).filter(Page.slug=='currentlevel')
        .join(page1, Page.parent).filter(page1.slug=="secondlevel")
        .join(page2, page1.parent).filter(page2.slug=="firstlevel")
        )

Or, using aliased (with from_joinpoint) arguments, somewhat shorter:

qry = (session
        .query(Page).filter(Page.slug=='currentlevel')
        .join(Page.parent, aliased=True).filter(Page.slug=="secondlevel")
        .join(Page.parent, aliased=True, from_joinpoint=True).filter(Page.slug=="firstlevel")
        )
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top