首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SQLAlchemy子查询执行但什么也不做

SQLAlchemy子查询执行但什么也不做
EN

Stack Overflow用户
提问于 2020-05-15 19:51:05
回答 1查看 54关注 0票数 1

在SQLAlchemy中应用左外部联接之前,我试图对右手项执行一个筛选器,由于某些原因,子查询似乎没有任何效果。

首先,我知道我应该从我的加入中得到12个结果:

代码语言:javascript
复制
startTimestampString = "2020-05-15T17:25:55"
itemRows = Item.query.filter(Item.timestamp > startTimestampString).all()
print(f"target # itemRows: {len(itemRows)}")
# target # itemRows: 12

但是,当我在join中实际应用子查询时,我从join的右侧获得所有575项,而不是:

代码语言:javascript
复制
subq = Item.query.filter(Item.timestamp > startTimestampString).subquery()
statusRows = Status.query.outerjoin(subq, Status.serviceID == subq.c.serviceID)\
print(f"returned # of subquery item rows: {sum([len(row.items) for row in statusRows])}")
# returned # of subquery item rows: 575

我在这里做了什么错事,使子查询实际上不应用任何筛选?

还有一些版本信息FWIW:

代码语言:javascript
复制
$ pip3 list|grep alchemy
Flask-SQLAlchemy       2.4.1
marshmallow-sqlalchemy 0.21.0
SQLAlchemy             1.3.12
SQLAlchemy-JSONField   0.9.0
SQLAlchemy-Utils       0.36.1

我通过postgresql+psycopg2连接到我的数据库,所以这个版本:

代码语言:javascript
复制
$ pip3 list|grep psy
psycopg2-binary        2.8.5
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-15 21:06:01

您忘记告诉ORM,您正在使用一个联接从子查询中加载一组过滤过的项:

代码语言:javascript
复制
subq = Item.query.filter(Item.timestamp > startTimestampString).subquery()
item_alias = db.aliased(Item, subq)
statusRows = Status.query.\
    outerjoin(item_alias, Status.serviceID == item_alias.serviceID).\
    options(db.contains_eager(Status.items, alias=item_alias))

如果没有contains_eager(),访问items关系属性的Status将在其默认配置中获取完整的项集。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61827245

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档