Django - __str__ 方法不起作用,说名称未定义
Django - __str__ method not working, says name is not defined
我定义了以下模型。
class Response(models.Model):
question = models.ForeignKey(Question, on_delete = models.CASCADE)
STATEMENT_CHOICES = (
(-1, "Strongly Disagree"),
(-0.5, "Somewhat Disagree"),
(0, "Uncertain"),
(0.5, "Somewhat Agree"),
(1, "Strongly Agree"),
)
statement = models.DecimalField(
max_digits=2,
decimal_places=1,
choices = STATEMENT_CHOICES
)
def __str__(self):
return self.statement
当我 运行 django shell 时,我创建了一个问题 q
说 you like pizza
和响应 r
即 1
strongly agree
。然后当我 运行 r
上的 __str__
方法时,我收到一条错误消息 name 'statement' is not defined
。
这是准确的控制台输出...
>>> q
<Question: You like pizza.>
>>> r = Response(question=q, statement=1)
>>> r.question
<Question: You like pizza.>
>>> r.statement
1
>>> r
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/TN/Documents/Programming/Django/Practice/myve /lib/python3.5/site-packages/django/db/models/base.py", line 572, in __repr__
u = six.text_type(self)
File "/Users/TN/Documents/Programming/Django/Practice/mysite/personalityQuiz/models.py", line 48, in __str__
return self.statement
NameError: name 'statement' is not defined
使用self.get_statement_display()
来return选择的说明。有关详细信息,请参阅 the docs。
我定义了以下模型。
class Response(models.Model):
question = models.ForeignKey(Question, on_delete = models.CASCADE)
STATEMENT_CHOICES = (
(-1, "Strongly Disagree"),
(-0.5, "Somewhat Disagree"),
(0, "Uncertain"),
(0.5, "Somewhat Agree"),
(1, "Strongly Agree"),
)
statement = models.DecimalField(
max_digits=2,
decimal_places=1,
choices = STATEMENT_CHOICES
)
def __str__(self):
return self.statement
当我 运行 django shell 时,我创建了一个问题 q
说 you like pizza
和响应 r
即 1
strongly agree
。然后当我 运行 r
上的 __str__
方法时,我收到一条错误消息 name 'statement' is not defined
。
这是准确的控制台输出...
>>> q
<Question: You like pizza.>
>>> r = Response(question=q, statement=1)
>>> r.question
<Question: You like pizza.>
>>> r.statement
1
>>> r
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/TN/Documents/Programming/Django/Practice/myve /lib/python3.5/site-packages/django/db/models/base.py", line 572, in __repr__
u = six.text_type(self)
File "/Users/TN/Documents/Programming/Django/Practice/mysite/personalityQuiz/models.py", line 48, in __str__
return self.statement
NameError: name 'statement' is not defined
使用self.get_statement_display()
来return选择的说明。有关详细信息,请参阅 the docs。