これは、問題の例と理想的でない回避策です。このサンプルモデルを見てください:
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')
この集計クエリの例は、を使用して作成された非フィールド値を参照しようとするため、同じように失敗します.extra()
。
User.ratings_received.extra(
select={'percent_positive': 'ratings > 3'}
).aggregate(count=Avg('positive'))
1つの回避策
目的の値は、追加の値の定義内で集約データベース関数(この場合はAvg)を使用して直接見つけることができます。
User.ratings.extra(
select={'percent_positive': 'AVG(rating >= 3)'}
)
このクエリは、次のSQLクエリを生成します。
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
このクエリには不要な列がありますが、値を分離することで、そこから目的の値を取得できpercent_positive
ます。
User.ratings.extra(
select={'percent_positive': 'AVG(rating >= 3)'}
).values('percent_positive')[0]['percent_positive']