我有几个函数需要使用 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())
解决方案
我找到了最好的方法来做到这一点。只需提供 afrom_statement
而不是 afilter_by
或一些这样的。像这样:
meta.Session.query(Location).from_statement(query).all()