TypeError: 'choice_text' 是 Django 教程中此函数的无效关键字参数

0 投票
1 回答
2992 浏览
提问于 2025-04-17 15:00

我正在学习这个教程:https://docs.djangoproject.com/en/1.4/intro/tutorial01/

在教程的最后部分,有一段关于django数据库API的内容,里面提到:

# Display any choices from the related object set -- none so far.
>>> p.choice_set.all()
[]

# Create three choices.
>>> p.choice_set.create(choice_text='Not much', votes=0)
<Choice: Not much>

但是当我直接复制教程中的这行代码:>>> p.choice_set.create(choice_text='Not much', votes=0)时,我遇到了:

raise TypeError("'%s' is an invalid keyword argument for this function" % kw
args.keys()[0])
TypeError: 'choice_text' is an invalid keyword argument for this function

之前教程中的所有内容都运行得很好。

你知道问题出在哪里吗?我刚开始学python,之前是用php,有一些面向对象编程的经验。

提前谢谢你,

比尔

1 个回答

5

你确定你是直接从教程里复制的吗?看起来应该是 choice= 而不是 choice_text=

# Create three choices.
>>> p.choice_set.create(choice='Not much', votes=0)
<Choice: Not much>
>>> p.choice_set.create(choice='The sky', votes=0)
<Choice: The sky>

这个模型是:

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice = models.CharField(max_length=200)
    votes = models.IntegerField()

这一行的作用是通过使用 choice_set.create() (文档链接),它在创建一个 Choice 模型,并把投票的内容 - p - 作为模型字段 poll(外键)来关联。然后把 choice= 的值赋给模型字段 choice,把 votes= 的值赋给模型字段 votes

撰写回答