﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
13461	Reference to aggregated field AND double underscore notation results in bad SQL	Vasily Ivanov	nobody	"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?"	Bug	closed	Database layer (models, ORM)	1.1	Normal	fixed		bas@…	Accepted	0	0	0	0	0	0
