Opened 9 years ago

Closed 6 years ago

#13461 closed Bug (fixed)

Reference to aggregated field AND double underscore notation results in bad SQL

Reported by: Vasily Ivanov Owned by: nobody
Component: Database layer (models, ORM) Version: 1.1
Severity: Normal Keywords:
Cc: bas@… Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


I have simple model like this one:

class Plan(models.Model):
	cap = models.IntegerField()

class Phone(models.Model):
	plan = models.ForeignKey(Plan, related_name='phones')

class Call(models.Model):
	phone = models.ForeignKey(Phone, related_name='calls')
	cost = models.IntegerField()

Call to:


results in error:

ProgrammingError: column "app_plan.cap" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: ...."plan_id" HAVING SUM("app_call"."cost") >=  0.5 * "app_plan"....

Generated SQL is:

SELECT "app_phone"."id", "app_phone"."plan_id", SUM("app_call"."cost") AS "total_cost"
FROM "app_phone"
INNER JOIN "app_plan" ON ("app_phone"."plan_id" = "app_plan"."id")
LEFT OUTER JOIN "app_call" ON ("app_phone"."id" = "app_call"."phone_id")
GROUP BY "app_phone"."id", "app_phone"."plan_id"
HAVING SUM("app_call"."cost") >=  0.5 * "app_plan"."cap"

Is it Django bug?

Change History (8)

comment:1 Changed 9 years ago by Vasily Ivanov

Cc: bas@… added

comment:2 Changed 9 years ago by Russell Keith-Magee

Triage Stage: UnreviewedAccepted

comment:3 Changed 9 years ago by Vasily Ivanov

I don't know how to modify ticket description here, but in case someone can see ambiguity here I'd like Django to add "app_plan"."cap" column into GROUP BY clause in this particular case.

comment:5 Changed 8 years ago by Julien Phalip

Severity: Normal
Type: Bug

comment:6 Changed 7 years ago by Aymeric Augustin

UI/UX: unset

Change UI/UX from NULL to False.

comment:7 Changed 7 years ago by Aymeric Augustin

Easy pickings: unset

Change Easy pickings from NULL to False.

comment:8 Changed 6 years ago by Anssi Kääriäinen

Resolution: fixed
Status: newclosed

This seems to be fixed in master, see aggregation_regress/test_aggregate_fexpr()

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