我是python和Django世界的新手。我不知道是否存在以下更好的方法:
#retrieve account row, correct soc code and save record.
for i in xrange(0,len(accIdList)):
acc = account.objects.filter(id=accIdList[i])[0]
acc.soc = getAccSocCode(acc)
acc.save()
def getAccSocCode(acc):
#apply business rules on acc
# and return new soc code
return socCode
这就是我的代码现在正在做的事情:
在这里,我将分别更新每个帐户行,是否有更好的方法,如下所示:
#retrieve account row, correct soc code and save record.
accList = []
for i in xrange(0,len(accIdList)):
acc = account.objects.filter(id=accIdList[i])[0]
acc.soc = getAccSocCode(acc)
accList.append(acc)
accList.save()
我尝试了上面的代码,但抛出错误,提示AttributeError: 'list' object has no attribute 'save'
简而言之,如何在Django中执行批量更新?
答案 0 :(得分:1)
使用F个对象-参见:How to 'bulk update' with Django?。
即使您要一一保存,也应将代码更改为:
for id in accIdList:
acc = account.objects.get(id)
acc.soc = getAccSocCode(acc)
acc.save()