Opened 2 years ago

Closed 2 years ago

#34206 closed Bug (invalid)

annotation of another annotation duplicate query rule

Reported by: Mohammad99k Owned by: Mohammad karimi
Component: Database layer (models, ORM) Version: 4.1
Severity: Normal Keywords: annotate
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

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`,

Change History (7)

comment:1 by Mohammad99k, 2 years ago

Component: UncategorizedDatabase layer (models, ORM)

comment:2 by Mohammad99k, 2 years ago

Type: Cleanup/optimizationBug

comment:3 by Mohammad99k, 2 years ago

Owner: changed from nobody to Mohammad karimi
Status: newassigned

comment:4 by Mariusz Felisiak, 2 years ago

Resolution: invalid
Status: assignedclosed

Thanks for this ticket, however, as far as I'm aware, your proposition is not doable as aliases cannot be created and used in the same SELECT clause (see also #10060 and docs). If you're having trouble getting the result you want, see TicketClosingReasons/UseSupportChannels for ways to get help.

comment:5 by Mohammad99k, 2 years ago

Resolution: invalid
Status: closednew

in reply to:  4 comment:6 by Mohammad99k, 2 years ago

Replying to Mariusz Felisiak:

Thanks for this ticket, however, as far as I'm aware, your proposition is not doable as aliases cannot be created and used in the same SELECT clause (see also #10060 and docs). If you're having trouble getting the result you want, see TicketClosingReasons/UseSupportChannels for ways to get help.

How can I fixed this issue?

comment:7 by Mariusz Felisiak, 2 years ago

Resolution: invalid
Status: newclosed

Please use one of support channels for support questions.

Note: See TracTickets for help on using tickets.
Back to Top