Sqlalchemy:joinedload+limi

2024-06-02 02:08:05 发布

您现在位置:Python中文网/ 问答频道 /正文

给出以下声明:

p = db.query(Profile).options(joinedload('*')).filter_by(id=p.id).limit(1).one()

我将得到一个子查询+一个联接,而不是一个“纯”联接:

^{pr2}$

但我真正需要的是:

SELECT ...
FROM profile LEFT OUTER JOIN city AS city_1 ON city_1.id = profile.city LEFT OUTER JOIN country AS country_1 ON country_1.id = city_1.country LEFT OUTER JOIN state AS state_1 ON country_1.id = state_1.country LEFT OUTER JOIN state AS state_2 ON state_2.id = city_1.state     
LEFT OUTER JOIN country AS country_2 ON country_2.id = state_2.country LEFT OUTER JOIN state AS state_3 ON state_3.id = city_1.state LEFT OUTER JOIN country AS country_3 ON country_3.id = state_3.country LEFT OUTER JOIN starred AS starred_1 ON profile.id = starred_1.star LEFT OUTER JOIN profiletext AS profiletext_1 ON profile.id = profiletext_1.profile LEFT OUTER JOIN starred AS starred_2 ON profile.id = starred_2.idprofile LEFT OUTER JOIN photo AS photo_1 ON profile.id = photo_1.profile LEFT OUTER JOIN gps AS gps_1 
ON profile.id = gps_1.idprofile                                                                                                                                                                                                    
WHERE profile.id = 4 
limit 1;

即没有子查询。在

数据库:postgresql 9.2


Tags: idcityonasprofileleftcountrygps
1条回答
网友
1楼 · 发布于 2024-06-02 02:08:05

这似乎是根据The Zen of Eager Loading的预期行为

When using joined eager loading, if the query contains a modifier that impacts the rows returned externally to the joins, such as when using DISTINCT, LIMIT, OFFSET or equivalent, the completed statement is first wrapped inside a subquery, and the joins used specifically for joined eager loading are applied to the subquery. SQLAlchemy’s joined eager loading goes the extra mile, and then ten miles further, to absolutely ensure that it does not affect the end result of the query, only the way collections and related objects are loaded, no matter what the format of the query is.

我知道这是一个老问题,但是生成的SQL不工作有什么原因吗?在

相关问题 更多 >