#34206: annotation of another annotation duplicate query rule
------------------------------------------------+--------------------------
               Reporter:  Mohammad99k           |          Owner:  nobody
                   Type:  Cleanup/optimization  |         Status:  new
              Component:  Uncategorized         |        Version:  4.1
               Severity:  Normal                |       Keywords:  annotate
           Triage Stage:  Unreviewed            |      Has patch:  0
    Needs documentation:  0                     |    Needs tests:  0
Patch needs improvement:  0                     |  Easy pickings:  0
                  UI/UX:  0                     |
------------------------------------------------+--------------------------
 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`,
 }}}

-- 
Ticket URL: <https://code.djangoproject.com/ticket/34206>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/01070184f69d72a6-b5b7a7fe-91b5-499b-8367-68372046f289-000000%40eu-central-1.amazonses.com.

Reply via email to