简体   繁体   English

将字典保存到模型对象

[英]Save dictionary to model object

I have a dictionary like this one: 我有一本这样的字典:

{'company_name': 'Google', 'title': 'headline', ...}

I know that i can store the values using this way: 我知道我可以使用以下方式存储值:

user = User(company_name=data_db_form['company_name'], title=data_db_form['title']...)

However this is not good if I have many form fields. 但是,如果我有很多表单字段,那么这不好。

There is any way to do this without hard code all the maps? 有没有硬编码所有地图的方法? The key value of the dictionary is the same of his model. 字典的键值与其模型相同。

You can use the following: 您可以使用以下内容:

user = User(**data_db_form)


Here is the full example: 这是完整的示例:

class User():
    def __init__(self, company_name='unknown', title='unknown'):
        self.company_name = company_name
        self.title = title

data_db_form = {'company_name': 'Google', 'title': 'headline'}

user = User(**data_db_form)

print user.company_name # prints Google
print user.title        # prints headline

使用for key, value in dic.iteritems():字典,然后在每次迭代中,key中都有company_nametitlefor key, value in dic.iteritems():则有Googleheadline等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM