How to use avg and sum in SQLAlchemy query

后端 未结 3 895
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-01 13:38

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:

S         


        
相关标签:
3条回答
  • 2021-02-01 13:58

    ttention = Attention_scores.query.with_entities(func.avg(Attention_scores.score)).filter(classroom_number == classroom_number).all()

    i tried like this . it gave the correct average

    0 讨论(0)
  • 2021-02-01 14:03

    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)
    
    0 讨论(0)
  • 2021-02-01 14:11

    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.

    0 讨论(0)
提交回复
热议问题