可以说我有
import peewee
class Foo(Model):
name = CharField()
Run Code Online (Sandbox Code Playgroud)
我想做以下事情:
f = {id:1, name:"bar"}
foo = Foo.create_from_dict(f)
Run Code Online (Sandbox Code Playgroud)
这是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
Run Code Online (Sandbox Code Playgroud)
我有一个显示所有foos的网页,允许用户编辑它们.我希望能够将JSON字符串传递给控制器,在那里我将它转换为dict,然后从中制作Foos,因此我可以根据需要进行更新.
col*_*fer 12
如果你有一个词典,你可以简单地说:
class User(Model):
name = CharField()
email = CharField()
d = {'name': 'Charlie', 'email': 'foo@bar.com'}
User.create(**d)
Run Code Online (Sandbox Code Playgroud)