设置django模型实例字段,例如字典

时间:2018-07-28 02:08:41

标签: python django model

在django中,我们可以更新模型实例字段,例如:

from .models import Credentials
current_cre=Credentials.object.get(user=request.user)

current_cre.fb_name='Name'
current_cre.fb_pass='****'
current_cre.save()

有什么办法可以像字典项目那样

current_cre['fb_name']='Name'
current_cre['fb_pass']='Pass'

所以我可以像这样迭代该过程

for field_name in List_Fields:
    current_cre[field_name]=request.POST[field_name]

提前谢谢。

2 个答案:

答案 0 :(得分:0)

尝试一下

List_Fields = [(f.verbose_name, f.name) for f in Credentials._meta.get_fields()]

for field_name, value in List_Fields:
    current_cre[field_name]=request.POST[field_name]

答案 1 :(得分:0)

您可以为此使用内置的__dict__

from .models import Credentials

current_cre = Credentials.object.get(user=request.user)
current_cre.__dict__['fb_name'] = "Name"
current_cre.__dict__['fb_pass'] = "****"
current_cre.save()


如果userunique字段,那么您也可以尝试一下,

from .models import Credentials

my_dict = {"fb_name": "Name", "fb_pass": "****"}
current_cre = Credentials.object.filtert(user=request.user).update(**my_dict)