我想用字符串作为键来更改Django字段的数据。
例子:
person = Person.objects.get(pk=1) person['name'] = 'John' person.save()
我的代码:
changes: dict[str, Any] = json.loads(request.body) user: User = User.objects.get(id=user_id) for key in changes.keys(): user[key] = changes.get(key) user.save() response = json.dumps([{ 'Success' : 'User changed successfully!'}]) return HttpResponse(response, content_type='application/json')
我收到以下错误消息:
TypeError:“用户”对象不支持项分配
我该怎么做?
非常感谢。
您还可以指定 updated_fields 除了保存其他答案外,还保存对象时:
updated_fields
updated_fields = [] for key, value in changes.items(): if hasattr(user, key): setattr(user, key, value) updated_fields.append(key) user.save(update_fields=updated_fields)
你可以用 **<dict_name> ( dictionary unpacking )要就地更新模型字段值,请执行以下操作:
**<dict_name>
User.objects.filter(id=user_id).update(**changes)
要使用setattr:
for key in changes.keys(): setattr(user, key, changes.get(key)) user.save()