I have to build a field from an annotation, the field is a score which is equal to the division of two other annotations which are based on different Querysets Expressions.
annotated_queryset = Influencer.objects.annotate(
score_sum=Sum('submission__answer__decisions__score'),
submission_count=Count('submission',
filter=Q(
submission__status__in=Submission.ANSWERED_STATUS
)
)
).annotate(rate=F('score_sum') / F('submission_count'))
This snippet shows how i get my annotation.
Now i'd love to be able to do the following :
annotated_queryset.update(acceptation_rate=F('rate'))
But I get a FieldError: Aggregate functions are not allowed in this query
My only solutions is to use the ugly and expensive for loop :
for each in annotated_queryset:
each.acceptation_rate = each.rate
each.save()
My questions are :
- Why can't I use the annotate + update form ?
- Is there any better way than the for loop to do this ? What would it be ?
Edit, Using Subqueries :
annotated_queryset = Influencer.objects.annotate(
score_sum=Sum('submission__answer__score'),
submission_count=Count('submission',
filter=Q(
submission__status__in=Submission.ANSWERED_STATUS
)
)
).annotate(
rate=ExpressionWrapper(
F('score_sum') / F('submission_count'),
output_field=FloatField()
)
)[:1]
Influencer.objects.update(acceptation_rate=Subquery(annotated_queryset))