Django - __str__方法不起作用,称名称未定义

时间:2017-11-28 18:33:26

标签: python django django-models nameerror

我定义了以下模型。

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。然后当我在__str__上运行r方法时,我收到错误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

1 个答案:

答案 0 :(得分:1)

使用self.get_statement_display()返回选择说明。有关详细信息,请参阅the docs