gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:27:22 24 4
gpt4 key购买 nike

我定义了以下模型。

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 表示强烈同意。然后,当我在 r 上运行 __str__ 方法时,出现错误,提示 name 'statement' is not Define

这是确切的控制台输出...

>>> 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()返回选项的描述。请参阅the docs了解更多信息。

关于python - Django - __str__ 方法不起作用,表示名称未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47538602/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com