Opened 10 years ago

Closed 10 years ago

#24222 closed Bug (fixed)

UnboundLocalError: local variable 'sql' referenced before assignment

Reported by: Oscar Esgalha Owned by: nobody
Component: Database layer (models, ORM) Version: 1.7
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

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

Change History (2)

comment:1 by Peter Inglesby, 10 years ago

This is fixed in 1.8, and was fixed by this commit.

comment:2 by Tim Graham, 10 years ago

Resolution: fixed
Status: newclosed
Note: See TracTickets for help on using tickets.
Back to Top