仅使用字符串作为键更改 Django 字段
Change Django field with only the string as a key
我想更改 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: 'User' object does not support item assignment
我应该怎么做?
谢谢!
您想使用 setattr:
for key in changes.keys():
setattr(user, key, changes.get(key))
user.save()
您可以使用 **<dict_name>
(dictionary unpacking) 来更新模型字段值:
User.objects.filter(id=user_id).update(**changes)
除了其他答案外,您还可以在保存对象时指定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)
我想更改 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: 'User' object does not support item assignment
我应该怎么做?
谢谢!
您想使用 setattr:
for key in changes.keys():
setattr(user, key, changes.get(key))
user.save()
您可以使用 **<dict_name>
(dictionary unpacking) 来更新模型字段值:
User.objects.filter(id=user_id).update(**changes)
除了其他答案外,您还可以在保存对象时指定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)