Peewee - 如何将字典转换为模型
假设我有以下内容:
import peewee
class Foo(Model):
name = CharField()
我想要做以下事情:
f = {id:1, name:"bar"}
foo = Foo.create_from_dict(f)
在Peewee中有这个功能吗?我在源代码中没有找到相关内容。
我写了一个函数可以实现这个功能,但如果有现成的函数我更想用它:
#clazz is a string for the name of the Model, i.e. 'Foo'
def model_from_dict(clazz, dictionary):
#convert the string into the actual model class
clazz = reduce(getattr, clazz.split("."), sys.modules[__name__])
model = clazz()
for key in dictionary.keys():
#set the attributes of the model
model.__dict__['_data'][key] = dictionary[key]
return model
我有一个网页,可以显示所有的foo
,并允许用户编辑它们。我想把一个JSON字符串传递给控制器,然后把它转换成字典,这样我就可以根据需要创建Foos并进行更新。
2 个回答
-2
你可以使用 PickledKeyStore,这个工具可以让你把任何值保存为一个Python字典,它的工作方式和 Python的pickle 库很像。
14
如果你有一个字典(dict),你可以简单地:
class User(Model):
name = CharField()
email = CharField()
d = {'name': 'Charlie', 'email': 'foo@bar.com'}
User.create(**d)