Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

python - Defining a model class in Django shell fails

when I use the Django shell, it shows an error; this is the error:

>>> from django.db import models
>>> class Poll(models.Model):
...     question = models.CharField(max_length=200)
...     pub_date = models.DateTimeField('date published')
...
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "D:Python25libsite-packagesdjangodbmodelsase.py", line 51, in __new__
    kwargs = {"app_label": model_module.__name__.split('.')[-2]}
IndexError: list index out of range

What can I do?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The model definition must come in an application - the error you're seeing there is that it tries to take the __name__ model_module - which should be something like project.appname.models for projectappnamemodels.py - and get the app name, appname. In the interactive console, the module's __name__ is '__main__' - so it fails.

To get around this, you'll need to specify the app_label yourself in the Meta class;

>>> from django.db import models
>>> class Poll(models.Model):
...     question = models.CharField(max_length=200)
...     pub_date = models.DateTimeField('date published')
...     class Meta:
...         app_label = 'test'

For explanation of why you can do that, look at that file mentioned in the traceback, D:Python25libsite-packagesdjangodbmodelsase.py:

    if getattr(meta, 'app_label', None) is None:
        # Figure out the app_label by looking one level up.
        # For 'django.contrib.sites.models', this would be 'sites'.
        model_module = sys.modules[new_class.__module__]
        kwargs = {"app_label": model_module.__name__.split('.')[-2]}
    else:
        kwargs = {}

(Where meta is the Meta class, see just above in that file.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...