如何从字典值更新现有模型实例

Who*_*ami 2 python django django-models django-forms django-views

给定模型实例,例如 StackOverflow 是模型,并且

 obj = StackOverflow.objects.get(..somecondition)
 dict  = { 'rating' : 3, 'field1' : 'question', field2 : 'answer' }
Run Code Online (Sandbox Code Playgroud)

StackOverflow 模型具有字典中可用的所有键作为成员变量。

我想用字典值更新 obj 。

我怎样才能达到同样的目标?

sga*_*a62 5

obj = StackOverflow.objects.get(pk=1)
d  = { 'rating' : 3, 'field1' : 'question', 'field2' : 'answer' }

for i in d:
    setattr(obj, i, d[i])
obj.save()
Run Code Online (Sandbox Code Playgroud)

这将起作用,假设字典键对应于StackOverflow模型中的字段,并且字典值是有效的字段值。