当我使用Django Shell时,显示错误;这是错误:
>>> 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:\Python25\lib\site-packages\django\db\models\base.py", line 51, in __new__ kwargs = {"app_label": model_module.__name__.split('.')[-2]} IndexError: list index out of range
我能做什么?
该模型定义必须进来的应用程序-你所看到的错误,就在于它试图拿__name__ model_module-这应该是这样project.appname.models的project\appname\models.py-并获得应用程序的名称,appname。在交互式控制台中,模块的位置__name__为'__main__'-,因此失败。
__name__
model_module
project.appname.models
project\appname\models.py
appname
'__main__'
为了解决这个问题,您需要app_label在Meta课程中指定自己。
app_label
Meta
>>> 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'
为了解释为什么可以这样做,请查看回溯中提到的文件D:\Python25\lib\site- packages\django\db\models\base.py:
D:\Python25\lib\site- packages\django\db\models\base.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 = {}
(如果meta是Meta一流的,看到的只是上面在该文件中。)
meta