![](/img/trans.png)
[英]How can I add a new field from the other app's models.py to html in Django, Python
[英]Can't add new function to models/table class in django (python)
这是我目前遇到的问题:
__str__()
函数,如下所示: 。
from django.db import models
class Question(models.Model):
def __str__(self):
return self.question_text`
这是我的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
有人知道吗? 我对django完全陌生,而且我不确定100%在这里应该执行什么base.py。
Base.py可以在这里找到: https : //github.com/django/django/blob/master/django/db/models/base.py
你快到了
您需要在models.py文件之类的Question类中添加def __str__()
方法。
您的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方法。 models.Model
本身具有__str__
里面方法已经和你只是修改你自己的行为Question
的版本models.Model
PS。 如果您在python 2上,则方法名称应为__unicode__
而不是__str__
。
PPS。 一点点的OOP语言:如果“函数”是类的一部分,则称为“方法”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.