Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/310.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
使用带有ORM的标记OVER子句的Python SQLAlchemy查询_Python_Sqlalchemy - Fatal编程技术网

使用带有ORM的标记OVER子句的Python SQLAlchemy查询

使用带有ORM的标记OVER子句的Python SQLAlchemy查询,python,sqlalchemy,Python,Sqlalchemy,另一个问题是如何使用sqlalchemy上的OVER子句: 但是如何使用ORM来实现呢?我有点像: q = self.session.query(self.entity, func.count().over().label('count_over')) 当我调用q.all()并显示以下消息时,此操作失败: sqlalchemy.exc.InvalidRequestError: Ambiguous column name 'count(*) OVER ()' in result set! tr

另一个问题是如何使用sqlalchemy上的OVER子句:

但是如何使用ORM来实现呢?我有点像:

q = self.session.query(self.entity, func.count().over().label('count_over'))
当我调用
q.all()
并显示以下消息时,此操作失败:

sqlalchemy.exc.InvalidRequestError:
Ambiguous column name 'count(*) OVER ()' in result set! try 'use_labels' option on select statement
如何解决这个问题?

您的语法几乎正确,应该是这样的:

import sqlalchemy
q = self.session.query(
    self.entity,
    sqlalchemy.over(func.count()).label('count_over'),
)
文档中的示例:

from sqlalchemy import over
over(func.row_number(), order_by='x')

SQLAlchemy查询对象具有
with_entities
方法,可用于自定义查询返回的列列表:

Model.query.with_entities(Model.foo, func.count().over().label('count_over'))
导致以下SQL:

SELECT models.foo AS models_foo, count(*) OVER () AS count_over FROM models

你的函数是对的。使用它们产生预期结果的方法如下:

from sqlalchemy import func
q = self.session.query(self.entity, func.count(self.entity).over().label('count_over'))
这将产生一个
COUNT(*)
语句,因为没有指定
实体.字段
。我使用以下格式:

from myschema import MyEntity
from sqlalchemy import func
q = self.session.query(MyEntity, func.count(MyEntity.id).over().label('count'))
当然,如果有一个id字段的话。但是你得到了机械师:-)