我有几个函数需要使用count(),group_by和order_by进行一对多连接。我使用sqlalchemy.select函数来产生一个查询,该查询将返回一组id,然后我将迭代在单个记录上进行ORM选择。我想知道的是,如果有一种方法可以在单个查询中使用ORM来完成我需要的操作,那么我可以避免必须执行迭代。SQLAlchemy with count,group_by和order_by使用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()
举例在此处可能有用 – user890739 2015-10-23 18:25:17