Search code examples
pythondjangodjango-south

Django error: AttributeError: 'NoneType' object has no attribute 'db'


Has anyone seen this error before? It comes whenever I try to execute a query on a particular model of mine. Querying the db directly works fine and it doesn't happen with other models.

For example, it's triggered by something like:

MyModel.objects.get(name__iexact = 'an existent name')

I believe this started immediately after a database migration with South. I could roll back the migration but I don't want to make bad worse so I've come here first.

  • Django 1.3
  • PostgreSQL 8.4.8
  • Python 2.7.0
  • iPython 0.10.2
  • Ubuntu 10.10 64-bit

Any ideas?

ERROR: An unexpected error occurred while tokenizing input
The following traceback may be corrupted or invalid
The error message is: ('EOF in multi-line statement', (173, 0))

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)

/home/<path to python>/<ipython console> in <module>()

/home/<path to python>/python2.7/site-packages/django/db/models/manager.pyc in get(self, *args, **kwargs)
    130 
    131     def get(self, *args, **kwargs):
--> 132         return self.get_query_set().get(*args, **kwargs)
    133 
    134     def get_or_create(self, **kwargs):

/home/<path to python>/python2.7/site-packages/django/db/models/query.pyc in get(self, *args, **kwargs)
    342         if self.query.can_filter():
    343             clone = clone.order_by()
--> 344         num = len(clone)
    345         if num == 1:
    346             return clone._result_cache[0]

/home/<path to python>/python2.7/site-packages/django/db/models/query.pyc in __len__(self)
     80                 self._result_cache = list(self._iter)
     81             else:
---> 82                 self._result_cache = list(self.iterator())
     83         elif self._iter:
     84             self._result_cache.extend(self._iter)

/home/<path to python>/python2.7/site-packages/django/db/models/query.pyc in iterator(self)
    287 
    288                 # Store the source database of the object

--> 289                 obj._state.db = db
    290                 # This object came from the database; it's not being added.

    291                 obj._state.adding = False

AttributeError: 'NoneType' object has no attribute 'db'

Solution

  • Kicking myself for this one, especially given how obvious the error message makes it in retrospect.

    My migration had added a new field named "_state" to the model. This field collided with the _state attribute of the object referenced in line 289 of query.pyc above.

    So new lesson: no field can be named "_state" on a Django model.

    Should this be submitted as a bug report?