﻿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
24222	UnboundLocalError: local variable 'sql' referenced before assignment	Oscar Esgalha	nobody	"I have a model similar to this one:
{{{
class Sale(models.Model):
    price = models.DecimalField(max_digits=8, decimal_places=2)
    delivery_date = models.DateTimeField()
}}}
And I want to get the sum of sales per month, so I tried this:
{{{
models.Sale.objects.datetimes('delivery_date', 'month').annotate(Sum('price'))
}}}

Since datetimes returns a new QuerySet, I expected that code would work, but I stumbled on this error message:
{{{
Traceback (most recent call last):
  File ""<console>"", line 1, in <module>
  File ""/home/vagrant/.virtualenvs/awesomeapp/local/lib/python2.7/site-packages/django/db/models/query.py"", line 116, in __repr__
    data = list(self[:REPR_OUTPUT_SIZE + 1])
  File ""/home/vagrant/.virtualenvs/awesomeapp/local/lib/python2.7/site-packages/django/db/models/query.py"", line 141, in __iter__
    self._fetch_all()
  File ""/home/vagrant/.virtualenvs/awesomeapp/local/lib/python2.7/site-packages/django/db/models/query.py"", line 966, in _fetch_all
    self._result_cache = list(self.iterator())
  File ""/home/vagrant/.virtualenvs/awesomeapp/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py"", line 1130, in results_iter
    for rows in self.execute_sql(MULTI):
  File ""/home/vagrant/.virtualenvs/awesomeapp/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py"", line 775, in execute_sql
    sql, params = self.as_sql()
  File ""/home/vagrant/.virtualenvs/awesomeapp/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py"", line 133, in as_sql
    grouping, gb_params = self.get_grouping(having_group_by, ordering_group_by)
  File ""/home/vagrant/.virtualenvs/awesomeapp/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py"", line 586, in get_grouping
    if sql not in seen:
UnboundLocalError: local variable 'sql' referenced before assignment
}}}

So I took a look at the source code:
https://github.com/django/django/blob/1.7.3/django/db/models/sql/compiler.py#L586

And if I read it correctly: if the condition in line 582 is sufficed, then the var 'sql' is indeed unassigned in the line 586.


I'm using python 2.7.6 and Django 1.7.3
The database is MySQL 5.5"	Bug	closed	Database layer (models, ORM)	1.7	Normal	fixed			Unreviewed	0	0	0	0	0	0
