How to use avg and sum in SQLAlchemy query

送分小仙女□ 提交于 2020-03-17 05:04:21

问题


I'm trying to return a totals/averages row from my dataset which contains the SUM of certain fields and the AVG of others.

I could do this in SQL via:

SELECT SUM(field1) as SumFld, AVG(field2) as AvgFld 
FROM Rating WHERE url=[url_string]

My attempt to translate this into SQLAlchemy is as follows:

totals = Rating.query(func.avg(Rating.field2)).filter(Rating.url==url_string.netloc)

But this is erroring out with:

TypeError: 'BaseQuery' object is not callable

回答1:


You should use something like:

from sqlalchemy.sql import func
session.query(func.avg(Rating.field2).label('average')).filter(Rating.url==url_string.netloc)

You cannot use MyObject.query here, because SqlAlchemy tries to find a field to put result of avg function to, and it fails.




回答2:


You cannot use MyObject.query here, because SqlAlchemy tries to find a field to put result of avg function to, and it fails.

This isn't exactly true. func.avg(Rating.field2).label('average') returns a Column object (the same type object that it was given to be precise). So you can use it with the with_entities method of the query object.

This is how you would do it for your example:

Rating.query.with_entities(func.avg(Rating.field2).label('average')).filter(Rating.url == url_string.netloc)


来源:https://stackoverflow.com/questions/7143235/how-to-use-avg-and-sum-in-sqlalchemy-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!