For some reason peewee fn.AVG()
function returns int
values, while it is supposed to return float
.
If I execute the following raw SQL query in DB Browser:
SELECT players.name, AVG(marks.skill) FROM players
JOIN marks ON player_id = players.id
GROUP BY players.id;
I get the correct result:
Charname | 6.6
However, if I execute this Python code:
from peewee import *
import models
query = (
models.Player.select(
models.Player.name,
fn.AVG(models.Mark.skill).alias('skill'),
)
.join(models.Mark, JOIN.LEFT_OUTER)
.group_by(models.Player.id)
)
for q in query:
print(q.name, q.skill, type(q.skill))
I get the result as truncated int
:
Charname 6 int
What might be wrong?
I'm using SQLite, models.Mark.skill
is an IntegerField
.
CodePudding user response:
You'll want to chain .coerce(False)
to the fn.AVG()
- this tells Peewee that we don't want to treat the resulting aggregate as an integer (since this func is called with a single argument corresponding to an integer field):
query = (
models.Player.select(
models.Player.name,
fn.AVG(models.Mark.skill).coerce(False).alias('skill'),
)
.join(models.Mark, JOIN.LEFT_OUTER)
.group_by(models.Player.id)
)
Doc: http://docs.peewee-orm.com/en/latest/peewee/api.html#Function.coerce