Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python SQLAlchemy与count、group_by和order_一起使用ORM_Python_Sqlalchemy - Fatal编程技术网

Python SQLAlchemy与count、group_by和order_一起使用ORM

Python SQLAlchemy与count、group_by和order_一起使用ORM,python,sqlalchemy,Python,Sqlalchemy,我有几个函数需要使用count()、group_by和order_by进行一对多连接。我正在使用sqlalchemy.select函数生成一个查询,该查询将返回一组id,然后我对这些id进行迭代,对各个记录执行ORM选择。我想知道的是,是否有一种方法可以在单个查询中使用ORM来完成我所需要的工作,从而避免进行迭代 这是我现在正在做的一个例子。在这种情况下,实体是位置和导向,一对多映射。我正在尝试获取一个顶级位置的列表,根据它们与多少指南相关而排序 def popular_world_cities

我有几个函数需要使用count()、group_by和order_by进行一对多连接。我正在使用sqlalchemy.select函数生成一个查询,该查询将返回一组id,然后我对这些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_语句
,而不是
filter_by
或类似的语句。像这样:

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

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


除此之外,我没有看到太多不明显的地方。

我找到了最好的方法。只需提供一个
from_语句
,而不是
filter_by
或类似的语句。像这样:

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

我发现这很困难,但SQLAlchemy确实支持
groupby
。查询下的文档没有这样说,但它确实支持它-我已经用过了


此外,您还可以使用订购方式。我本打算像您一样创建一个特殊的类/查询,但后来我发现有一个
groupby()
函数。

这里的示例可能很有用,例如(取自)
session.query(Table.column,func.count(Table.column)).groupby(Table.column).all()