When I use an annotation in another annotation, query is duplicated like bellow:
groups = StudyGroup.objects.filter(group_filter).select_related('parent').annotate(
no_members=Count('student', distinct=True),
point=Sum('student__point__point', filter=point_filter),
avg_point=ExpressionWrapper(F('point') / F('no_members'), output_field=FloatField()))
In above queryset, Count('student', distinct=True)
calculate for no_members and when I use no_members in avg_point annotation again query calculate Count('student', distinct=True)
instead of use no_members directly.
COUNT(DISTINCT `users_student`.`user_id`) AS `no_members`,
SUM(`study_league_point`.`point`) AS `point`,
(
SUM(`study_league_point`.`point`) / COUNT(DISTINCT `users_student`.`user_id`)
) AS `avg_point`,
In above my SQL code COUNT(DISTINCT `users_student`.`user_id`)
is duplicate (SUM(`study_league_point`.`point`)
too).
my desired query is like this:
COUNT(DISTINCT `users_student`.`user_id`) AS `no_members`,
SUM(`study_league_point`.`point`) AS `point`,
(
point / no_members
) AS `avg_point`,