在Django shell中定义模型类失败 [英] Defining a model class in Django shell fails

查看:116
本文介绍了在Django shell中定义模型类失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用Django shell,它显示错误;这是错误:

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:\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

我可以做什么?

推荐答案

模型定义必须在一个应用程序中 - 你的错误看到它试图采取 __名称__ model_module - 这应该是像项目.appname.models for project\appname\models.py - 并获取应用程序名称, appname 。在交互式控制台中,模块的 __ name __ '__ main __' - 所以它失败。

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 project\appname\models.py - and get the app name, appname. In the interactive console, the module's __name__ is '__main__' - so it fails.

要解决这个问题,您需要在 Meta app_label > class;

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'

为了解释为什么你可以这样做,查看追溯中提到的文件, D:\Python25\lib\site-packages\django\db\models\base.py

For explanation of why you can do that, look at that file mentioned in the traceback, 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 类,请参见该文件的上方。)

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

这篇关于在Django shell中定义模型类失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆