Here is an example of the problem and an unideal workaround solution. Take this example model:
class Rating(models.Model):
RATING_CHOICES = (
(1, '1'),
(2, '2'),
(3, '3'),
(4, '4'),
(5, '5'),
)
rating = models.PositiveIntegerField(choices=RATING_CHOICES)
rater = models.ForeignKey('User', related_name='ratings_given')
ratee = models.ForeignKey('User', related_name='ratings_received')
This example aggregate query fails in the same way as yours because it attempts to reference a non-field value created using .extra()
.
User.ratings_received.extra(
select={'percent_positive': 'ratings > 3'}
).aggregate(count=Avg('positive'))
One Workaround Solution
The desired value can be found directly by using the aggregate database function (Avg in this case) within the extra value's definition:
User.ratings.extra(
select={'percent_positive': 'AVG(rating >= 3)'}
)
This query will generate the following SQL query:
SELECT (AVG(rating >= 3)) AS `percent_positive`,
`ratings_rating`.`id`,
`ratings_rating`.`rating`,
`ratings_rating`.`rater_id`,
`ratings_rating`.`ratee_id`
FROM `ratings_rating`
WHERE `ratings_rating`.`ratee_id` = 1
Despite the unneeded columns in this query, we can still obtain the desired value from it by isolating the percent_positive
value:
User.ratings.extra(
select={'percent_positive': 'AVG(rating >= 3)'}
).values('percent_positive')[0]['percent_positive']