Py学习  »  Django

仅使用字符串作为键更改Django字段

lionel • 3 年前 • 1077 次点击  

我想用字符串作为键来更改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:“用户”对象不支持项分配

我该怎么做?

非常感谢。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/130838
 
1077 次点击  
文章 [ 3 ]  |  最新文章 3 年前
kamilyrb
Reply   •   1 楼
kamilyrb    3 年前

您还可以指定 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)
Rustam Garayev
Reply   •   2 楼
Rustam Garayev    3 年前

你可以用 **<dict_name> ( dictionary unpacking )要就地更新模型字段值,请执行以下操作:

User.objects.filter(id=user_id).update(**changes)
jmcarson
Reply   •   3 楼
jmcarson    3 年前

要使用setattr:

for key in changes.keys():
  setattr(user, key, changes.get(key))

user.save()