Search code examples
pythonormpeewee

Creating AVG query with Peewee in Python


Im using Peewee ORM. I have only one table (Person) with fields like first_name, username, age, gender etc. I want to write a query where I get average of age, just like normal SQL query:

SELECT AVG(age) FROM Person

But I have problem with creating this query in Peewee. I have:

query = Person.select(fn.AVG(Person.age))

When I print this query I get: SELECT AVG("t1"."age") FROM "person" as "t1" and when I iterate over query and and print I get None. Does anybody know how to solve this problem?


Solution

  • To get a scalar value, from an aggregate, you can use the scalar() method:

    Person.select(fn.AVG(Person.age)).scalar()
    

    http://docs.peewee-orm.com/en/latest/peewee/querying.html#aggregating-records