﻿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
13274	Grouping in sql adds everything in extra select.	Vadim Fint	nobody	"Why so?

E.g.

{{{
#!python
# (we are in app asdapp)
class Asd(Model):
   pass

class Other(Model):
  asd = models.ForeignKey(Asd)

qs = Asd.objects.extra(select={'super_extra': 'SELECT count(*) from asdapp.other WHERE asdapp_other.asd_id = asdapp_asd.id'})
# normal extra, isnt it?
# but if we add some groupping, all fails
qs.query.group_by = [('asdapp', 'id')]
print qs # error -- invalid query
# query will have stange groupping: something like ""(...) GROUP BY asdapp.id, SELECT COUNT(*) from asdapp.other WHERE asdapp_other.asd_id = asdapp_asd.id""
}}}

This is because code in compiler.get_groupping() just adds everything (!) in extra to groupping:

{{{
#!python
#django/django/db/models/sql/compiler.py
475                 extra_selects = []
476	            for extra_select, extra_params in self.query.extra_select.itervalues():
477	                extra_selects.append(extra_select)
478	                params.extend(extra_params)
479	            for col in group_by + self.query.related_select_cols + extra_selects:
480	                if isinstance(col, (list, tuple)):
481	                    result.append('%s.%s' % (qn(col[0]), qn(col[1])))
482	                elif hasattr(col, 'as_sql'):
483	                    result.append(col.as_sql(qn))
484	                else:
485	                    result.append('(%s)' % str(col))
}}}

Why the hell django explicity tries to add extra cols to groupping? IMHO, this only should be done by developer itself (if he needs that behaviour).

Extra is usually a subquery. There is no much reason to make {{{ extra(select={'col_alias': 'real_col'}) }}} (this way grouping will work). Maybe somebody wanted an {{{iterkeys()}}} against {{{ query.extra_select }}} in line 476? :)"		closed	Database layer (models, ORM)	dev		invalid			Unreviewed	0	0	0	0	0	0
