For a poll app, I want the product_code
, Count()
and proprtion of product ratings > 3 for each product rating ("Product_r
") object (grouped on product_code
).
I was hoping I could get away with a calculation in the last annotation expression, but it seems not.
q = Product_r.objects.all()\
.annotate(product_code=F('fk_product__product_code'))\
.values('product_code')\
.annotate(count=Count('id'))\
.annotate(proportion=Count(score__gt=3)/count)
The below attempt doesn't work either (complains that count
is not defined, and also it filters the whole query, not just the subsequent annotate part that calculates the proportion):
q = Product_r.objects.all()\
.annotate(product_code=F('fk_product__product_code'))\
.values('product_code')\
.annotate(count=Count('id'))\
.filter(score__gt=3)\
.annotate(proportion=Count('id')/count)
Is there a way to do this without coding the query twice (one of them filtering on score__gt=3
), and then dividing the two count
values? This blog post uses raw SQL for this sort of thing - I hope it's possible to avoid that in my case here.