Peewee - How to Convert a Dict into a Model

南笙酒味 提交于 2019-12-11 01:28:43

问题


Lets say I have

import peewee

class Foo(Model):
    name = CharField()

I would like to do the following:

f = {id:1, name:"bar"}
foo = Foo.create_from_dict(f)

Is this native in Peewee? I was unable to spot anything in the source code.

I've wrote this function which works but would rather use the native function if it exists:

#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

I have a web page that displays all the foos and allows the user to edit them. I would like to be able to pass a JSON string to the controller, where I would convert it to a dict and then make Foos out of it, so I can update as necessary.


回答1:


If you have a dict, you can simply:

class User(Model):
    name = CharField()
    email = CharField()

d = {'name': 'Charlie', 'email': 'foo@bar.com'}
User.create(**d)



回答2:


You could use PickledKeyStore which allows you to save any value as a python dict and it works like Python's pickle library.



来源:https://stackoverflow.com/questions/22750439/peewee-how-to-convert-a-dict-into-a-model

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!