49

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

3 Answers 3

77

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.

4
  • Thanks, I had a feeling it should be using session but wasn't understanding why. Now I get it, thanks for the help, it's working well now.
    – mal-wan
    Commented Aug 22, 2011 at 5:18
  • 7
    I think it would be good to mention, you have to import from sqlalchemy.sql import func Commented Feb 24, 2014 at 12:43
  • How session.query understood that it has to run this query in Rating Table ?
    – ted
    Commented Aug 25, 2016 at 11:03
  • @ted: Rating is defined in the above example in two places: 1) within func.avg() and 2) in filter() Commented Oct 11, 2017 at 17:50
56

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)
1
  • 8
    this is the correct answer because will the flask-sqlalchemy
    – anvd
    Commented Jun 30, 2015 at 0:01
2
attention = Attention_scores.query
    .with_entities(func.avg(Attention_scores.score))
    .filter(classroom_number == classroom_number)
    .all()

I tried it like this and it gave the correct average.

2
  • 1
    Please edit your question to add the correct format, also, please describe why does your answer works? and what was wrong?. Please take a look at our guidelines on how do I format my post?.
    – EnriqueBet
    Commented May 27, 2020 at 5:13
  • This doesn't add anything to the existing decade-old answers Commented Sep 3, 2022 at 9:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.