Can';t在django(python)中向模型/表类添加新函数

Can';t在django(python)中向模型/表类添加新函数,python,django,django-models,Python,Django,Django Models,以下是我目前面临的问题: 我正在Windows上使用命令提示符运行 我在models.py中创建了一个名为“Question”的表 我正试图在此类中创建一个\uuu str\uuu()函数,如下所示: 这就是my models.py的外观: from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date

以下是我目前面临的问题:

  • 我正在Windows上使用命令提示符运行
  • 我在models.py中创建了一个名为“Question”的表
  • 我正试图在此类中创建一个
    \uuu str\uuu()
    函数,如下所示:

这就是my models.py的外观:

from django.db import models

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
class Choice(models.Model):
    question = models.ForeignKey(Question)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
我收到的错误如下:

Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Python34\lib\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
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“C:\Python34\lib\site packages\django\db\models\base.py”,第117行,在新的__
kwargs={“应用程序标签”:包组件[应用程序标签索引]}
索引器:列表索引超出范围
有人知道吗?我对django完全不了解,我不确定base.py应该在这里做什么

Base.py可以在这里找到:

您就快到了

您需要在models.py文件中的Question类中添加
def\uu str\uuu()
方法,如

您的models.py应如下所示:

from django.db import models

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    def __str__(self):
        return self.question_text
class Choice(models.Model):
    question = models.ForeignKey(Question)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
    def __str__(self):
        return self.choice_text #or whatever u want here, i just guessed u wanted choice text
实际上,您所做的是重写正在子类化的类中的内置dunder方法<代码>模型。模型本身已经有一个
\uuuu str\uuuu
方法,您只是在
问题中修改它的行为

注:如果您使用的是Python2,那么方法名称应该是
\uuuuUnicode\uuuuuu
,而不是
\uuuuuuu str\uuuuuu

PPS。一点OOP语言:如果一个“函数”是一个类的一部分,它被称为一个“方法”

如果发生这种情况,请查看关于子分类/继承的文章,因为它通常有助于了解您为什么要做某些事情,以了解为什么它不起作用
from django.db import models

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    def __str__(self):
        return self.question_text
class Choice(models.Model):
    question = models.ForeignKey(Question)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
    def __str__(self):
        return self.choice_text #or whatever u want here, i just guessed u wanted choice text