我们正在尝试将遗留代码的django版本从1.8升级到1.9。我们有一个定义如下的模型:
def _get_descendant_question_classes():
stack = [Question]
while stack:
cls = stack.pop()
stack.extend(cls.__subclasses__())
yield cls
def _get_question_choices():
question_classes = _get_descendant_question_classes()
for cls in question_classes:
yield (cls.slug, cls._meta.verbose_name)
class Question(models.Model):
slug = "Question"
type = models.CharField(max_length=10, choices=_get_question_choices(), default=slug)
class TextQuestion(Question):
slug = "TextQuestion"
class SelectQuestion(Question):
slug = "SelectQuestion"
...
此代码在django 1.8中工作,但在django 1.9中,它给出了以下错误:
Traceback (most recent call last):
File "./manage.py", line 16, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 350, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 324, in execute
django.setup()
File "/usr/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/usr/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/usr/local/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models
self.models_module = import_module(models_module_name)
File "/usr/local/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/saeed/saeed/survey/models.py", line 85, in <module>
class Question(models.Model):
File "/home/saeed/saeed/survey/models.py", line 99, in Question
type = models.CharField(max_length=10, choices=_get_question_choices(), default=slug)
File "/usr/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 1072, in __init__
super(CharField, self).__init__(*args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 161, in __init__
choices = list(choices)
File "/home/saeed/saeed/survey/models.py", line 65, in _get_question_choices
for cls in question_classes:
File "/home/saeed/saeed/survey/models.py", line 54, in _get_descendant_question_classes
stack = [Question]
NameError: global name 'Question' is not defined
我理解这个问题我不明白的是django1.8是如何工作的?django1.9中的哪些变化导致了这种情况?最好的解决方法是什么?