Opened 14 years ago

Closed 11 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

Description

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:

Phone.objects.annotate(total_cost=Sum('calls__cost')).filter(total_cost__gte=0.5*F('plan__cap'))

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 by Vasily Ivanov, 14 years ago

Cc: bas@… added

comment:2 by Russell Keith-Magee, 14 years ago

Triage Stage: UnreviewedAccepted

comment:3 by Vasily Ivanov, 14 years ago

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 by Julien Phalip, 13 years ago

Severity: Normal
Type: Bug

comment:6 by Aymeric Augustin, 12 years ago

UI/UX: unset

Change UI/UX from NULL to False.

comment:7 by Aymeric Augustin, 12 years ago

Easy pickings: unset

Change Easy pickings from NULL to False.

comment:8 by Anssi Kääriäinen, 11 years ago

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