#StackBounty: #python #django #django-models #django-1.8 #django-1.9 Using a model's sub-classes as choice options for that model r…

Bounty: 100

We are trying to upgrade a legacy code’s django version from 1.8 to 1.9. We have one model that is defined like this:

def _get_descendant_question_classes():
    stack = [Question]

    while stack:
        cls = stack.pop()
        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):
    type = models.CharField(max_length=10, choices=_get_question_choices(), default=slug)

class TextQuestion(Question): pass
class SelectQuestion(Question): pass

Basically the model wants to use its sub-classes as choice options for one of its fields. It does this with traversing the model in a DFS manner and yielding all the sub-classes.

This code works in django 1.8 but in django 1.9 it gives this error:

Traceback (most recent call last):
  File "./manage.py", line 16, in <module>
  File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 350, in execute_from_command_line
  File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 324, in execute
  File "/usr/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
  File "/usr/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
  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
  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

I understand the problem what I don’t understand is how this works in django 1.8? What has changed in django 1.9 that causes this? What is the best way to fix this?

Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.