Django保存模型数据触发'int' object is not callable错误的解决方法
修复TypeError: 'int' object is not callable错误
你遇到的这个错误原因很直观——你把模型的字段当成可调用的方法来使用了!
看代码里的这一行:
question.no_value(value)
这里的no_value是你模型中定义的IntegerField字段,它本质是一个属性(用来存储整数的变量),而不是可以通过()调用的方法。当你试图用括号传值时,Python会把当前no_value存储的整数(默认是0)当成函数去执行,这自然就抛出了int object is not callable的错误。
具体修复步骤
把字段的调用写法改成直接赋值即可,替换掉错误的那一行:
question.no_value = value
修正后的完整函数如下:
def _no_value(): questions = Question.objects.all() for question in questions: regex = re.compile('(__[_]*)') no_value = regex.findall(question.question) if no_value: value = len(no_value) # 直接给字段赋值,而非调用方法 question.no_value = value question.save()
额外提个小优化:如果你的场景不需要逐个处理Question实例的额外逻辑,使用Question.objects.update()批量更新会比循环逐个save()更高效,能减少数据库交互次数。
内容的提问来源于stack exchange,提问作者Vasu Pal
相关产品推荐
相关产品推荐

