简体   繁体   English

SQLAlchemy中的外键查询

[英]Foreign key querines in SQLAlchemy

I'm new to SQLAlchemy, after coming from Django ORM. 来自Django ORM之后,我还是SQLAlchemy的新手。 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: 我想在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: 在SQLAlchemy中,我能想到的最好的方法是:

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. 请记住,我是SQLAlchemy的新手,来自相对庇护的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. 我确定SQLAchemy文档中有信息,但我已经阅读了它,而且似乎找不到它。

Thanks for your help. 谢谢你的帮助。

You are right, all information in sqlalchemy docs under Self-Referential Query Strategies . 没错,sqlalchemy文档中“ 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: 或者,使用aliased (带有from_joinpoint )参数,稍微短一些:

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")
        )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM