SQLAlchemy使用ORM进行count,group_by和order_by

时间:2008-12-16 00:27:42

标签: python sqlalchemy

我有几个函数需要使用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()

3 个答案:

答案 0 :(得分:1)

您尝试执行的操作直接映射到子查询[由当前选择调用]和表格之间的SQLAlchemy连接。您将要从子选择中移出排序,并使用count(desc)创建一个单独的标记列;按该列排序外部选择。

除此之外,我认为这并不是很明显。

答案 1 :(得分:1)

我发现这很难,但SQLAlchemy确实支持group_by。 “查询”下的文档没有这么说,但确实支持它 - 我已经使用过它了!

而且,您也可以使用order_by。我打算像你一样创建一个特殊的类/查询,但后来发现有一个group_by()函数。

答案 2 :(得分:0)

我找到了最好的方法。只需提供from_statement而不是filter_by或其他类似内容。像这样:

meta.Session.query(Location).from_statement(query).all()