2

I'd like to annotate a field by using conditional expressions. However, Django ORM doesn't allow to compare Avg('rating') and 5. I could calculate average rating before the query but I don't know whether it's a proper and efficient way.

queryset = (
    Item.objects.filter(
        status='Live'
    ).annotate(
        group=Case(When(Avg('rating')=5, then=0))
    )
)
Burak Özdemir
  • 510
  • 8
  • 18

1 Answers1

1

did you try to annotate first the average and then go for the conditional expression? not sure about performance implications...by memory:

Item.objects.filter(
    status='Live'
).annotate(average_rating=Avg('rating').annotate(
    group=Case(When(average_rating=5, then=0))
)