Python:无法连接'str'和'long'对象

20

我正在尝试在Django中设置一个选择字段,但我认为这不是Django问题。 choices字段需要一个可迭代的对象(例如列表或元组)作为此字段的选择项。

这是我的代码:

self.fields['question_' + question.id] = forms.ChoiceField(
                label=question.label,
                help_text=question.description,
                required=question.answer_set.required,
                choices=[("fe", "a feat"), ("faaa", "sfwerwer")])

由于某些原因,我总是得到以下错误:

TypeError - cannot concatenate 'str' and 'long' objects

最后一行始终被突出显示。

我不是在尝试连接任何内容。几乎无论我将列表更改为“choices”参数的什么内容,都会出现此错误。

发生了什么?


请注意,“最后一行已突出显示”,因为它指向包含错误的多行语句。 - Andrew Jaffe
5个回答

36

很可能之所以只强调最后一行,是因为您将语句分成了多行。

解决实际问题的方法很可能是更改

self.fields['question_' + question.id]
self.fields['question_' + str(question.id)]

正如您可以在Python解释器中快速测试的那样,将字符串和数字相加不起作用:

>>> 'hi' + 6

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    'hi' + 6
TypeError: cannot concatenate 'str' and 'int' objects
>>> 'hi' + str(6)
'hi6'

6

'question_'是一个字符串,question.id是一个长整型。你不能将两个不同类型的东西拼接在一起,你需要使用str(question.id)将长整型转换为字符串。


2

可能 question.id 是一个整数。尝试:

self.fields['question_' + str(question.id)] = ...

取而代之。


2
self.fields['question_' + question.id]

那似乎是问题所在。请尝试。
"question_%f"%question.id

或者
"question_"+ str(question.id)

-2
这是在一行中做太多事情的问题 - 错误信息变得稍微不那么有帮助。如果您按照以下方式编写它,问题将更容易找到。
question_id = 'question_' + question.id
self.fields[question_id] = forms.ChoiceField(
                label=question.label,
                help_text=question.description,
                required=question.answer_set.required,
                choices=[("fe", "a feat"), ("faaa", "sfwerwer")])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接