Django错误:AttributeError: 'NoneType'对象没有属性'db
有没有人见过这个错误?每当我尝试在我的某个模型上执行查询时,就会出现这个错误。直接查询数据库是没问题的,其他模型也没有这个问题。
比如,它是由类似下面的代码引发的:
MyModel.objects.get(name__iexact = 'an existent name')
我觉得这个问题是在我用South进行数据库迁移后立刻出现的。我可以回滚这个迁移,但我不想让事情变得更糟,所以我先来这里问问。
- Django 1.3
- PostgreSQL 8.4.8
- Python 2.7.0
- iPython 0.10.2
- Ubuntu 10.10 64位
有什么想法吗?
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'
1 个回答
0
我真为这个感到懊恼,尤其是现在回头看错误信息时,感觉它实在太明显了。
我的迁移操作中添加了一个叫“_state”的新字段。结果这个字段和上面query.pyc第289行引用的对象的_state属性发生了冲突。
所以新的教训是:在Django模型中,字段不能命名为“_state”。
这应该作为一个bug报告提交吗?