﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
34206	annotation of another annotation duplicate query rule	Mohammad99k	Mohammad karimi	"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`,
}}}
"	Bug	closed	Database layer (models, ORM)	4.1	Normal	invalid	annotate		Unreviewed	0	0	0	0	0	0
