【发布时间】:2010-09-27 01:51:35
【问题描述】:
我有几个函数需要使用 count()、group_by 和 order_by 进行一对多连接。我正在使用 sqlalchemy.select 函数来生成一个查询,该查询将返回一组 id,然后我对其进行迭代以对各个记录进行 ORM 选择。我想知道是否有一种方法可以在单个查询中使用 ORM 来完成我需要做的事情,这样我就可以避免进行迭代。
这是我现在正在做的一个例子。在这种情况下,实体是位置和指南,一对多映射。我正在尝试获取按相关指南数量排序的热门地点列表。
def popular_world_cities(self):
query = select([locations.c.id, func.count(Guide.location_id).label('count')],
from_obj=[locations, guides],
whereclause="guides.location_id = locations.id AND (locations.type = 'city' OR locations.type = 'custom')",
group_by=[Location.id],
order_by='count desc',
limit=10)
return map(lambda x: meta.Session.query(Location).filter_by(id=x[0]).first(), meta.engine.execute(query).fetchall())
解决方案
我找到了最好的方法。只需提供 from_statement 而不是 filter_by 或类似的。像这样:
meta.Session.query(Location).from_statement(query).all()
【问题讨论】:
标签: python sqlalchemy