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 , 2 years ago
Component: | Uncategorized → Database layer (models, ORM) |
---|
comment:2 by , 2 years ago
Type: | Cleanup/optimization → Bug |
---|
comment:3 by , 2 years ago
Owner: | changed from | to
---|---|
Status: | new → assigned |
follow-up: 6 comment:4 by , 2 years ago
Resolution: | → invalid |
---|---|
Status: | assigned → closed |
comment:5 by , 2 years ago
Resolution: | invalid |
---|---|
Status: | closed → new |
comment:6 by , 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 , 2 years ago
Resolution: | → invalid |
---|---|
Status: | new → closed |
Please use one of support channels for support questions.
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.