I'm trying to write a function to calculate the average value of a nested json value in postgres via sqlalchemy. The value I'm trying to average is in a Statistics table, with a scores column that holds a json dictionary like this (filtered to the relevant structure): {1: {'score': 0.0}, 2: {'score': 0.0} ...}.
Written in postgres, the query looks like this:
SELECT *, avg((v->>'score')::float) AS average_score
FROM lms.statistics, jsonb_each(statistics.scores) js(k, v)
WHERE jsonb_typeof(scores) != 'null'
GROUP BY statistics.id
And I've cast it mostly into the following sqlalchemy code:
(
session.query(Statistics)
.add_columns(literal_column("avg((v->>'score')::float)").label('average_score'))
.filter(literal("jsonb_typeof(statistics.scores != 'null'"))
.group_by(Statistics.id)
).all()
However, no matter what I try to do, sqlalchemy simply won't allow me to include the jsonb_each this query depends on. I've even tried restructuring the query to use an explicit join, and sqlalchemy's .join won't accept literal_column, text, or any trickery with outer joins or specifying fake join conditions. I'm at the end of my rope trying to cheat this in, when there has to be an sqlalchemy standard to insert plaintext queries into FROM or JOIN statements.