对象不支持项分配错误

在我的 views.py中,我在保存表单之前赋值。我通常这样做:

projectForm.lat = session_results['lat']
projectForm.lng = session_results['lng']

现在,由于变量列表有点长,我想用下面的循环(如 Adam 给你所描述的)在 session_results上循环:

for k,v in session_results.iteritems():
projectForm[k] = v

但是我得到了循环解决方案的错误 'Project' object does not support item assignment。我不明白为什么。Project是我用于 ModelForm 的模型类。

谢谢你的帮助!

160294 次浏览

The error seems clear: model objects do not support item assignment. MyModel.objects.latest('id')['foo'] = 'bar' will throw this same error.

It's a little confusing that your model instance is called projectForm...

To reproduce your first block of code in a loop, you need to use setattr

for k,v in session_results.iteritems():
setattr(projectForm, k, v)

Another way would be adding __getitem__, __setitem__ function

def __getitem__(self, key):
return getattr(self, key)

You can use self[key] to access now.