学习 Django 教程。
python 3.4 Django 1.7
“等一下。完全是这个对象的无用表示。让我们通过编辑问题模型(在 polls/models.py 文件中)并添加 str() 来解决这个问题问题和选择的方法:"
>>> from django.db import models
>>> class Question(models.Model):
... def __str__(self):
... return self.question_text
...
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/models/base.py", line 117, in __new__
kwargs = {"app_label": package_components[app_label_index]}
IndexError: list index out of range
然后我在尝试编辑类 Choice(models.Model) 时也收到同样的错误。我希望这能为您提供足够的信息。让我知道我应该包括哪些其他信息。
最佳答案
问题是 Django 需要模型 to be created in specific places ,通常是 models.py
文件。这将允许 the app_label
meta field ,除其他外,自动生成。
from django.db import models
class Question(models.Model):
class Meta:
app_label = "something"
def __str__(self):
return self.question_text
由于您是在解释器中创建模型,因此您需要自行设置 app_label
元字段,因此 Django 不必猜测它应该在哪里。您可能还想考虑在解释器之外设置模型,因为它们应该在具体模块中并引用现有表。
如果您尝试为现有表生成模型,您还应该设置 the db_table
meta field . Django 会自动生成一个表名,它很可能与现有名称不匹配。
关于python - Django def __str__ 列表索引超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27591907/