Burak Özdemir
Burak Özdemir

Reputation: 560

Django ORM: Calculation of average result in conditional expression methods

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))
    )
)

Upvotes: 2

Views: 422

Answers (1)

user4691348
user4691348

Reputation:

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))
)

Upvotes: 1

Related Questions