How can I use dict_to_model()
to populate (insert data into) a table from dictionary values without changing the model attributes? I have a model, Video, with attributes:
class Video(model):
id = IntegerField()
camera = CharField()
channel = IntegerField()
filename = CharField()
I also have a dictionary of data:
data = {'video_id': 1234, 'camera_name': "canon", 'channel_id': 5, 'video_name' = "intro.mp4"}
Each key:value pair in the dict corresponds to a column and its data. From what I understand, I can use the dict_to_model
function from playhouse.shortcuts
to map the dict keys to table columns and act on the values inside the dict. How can I do this without changing the names of my class attributes? The only way I could get this to work was by changing Video.id to Video.video_id so it matches the dictionary and so on. Even then, a .save() statement does not push the data to a table. If I do not change my model attributes, I get:
AttributeError: Unrecognized attribute "video_id" for model class <Model: Video>
If I change my attributes to match the dictionary, it accepts the mapping but will not send the data to the table.
CodePudding user response:
Dict and model fields should match, so you have to rename either dict fields or model fields.
Also take a look at "Storing Data" section in peewee quickstart
uncle_bob = Person(name='Bob', birthday=date(1960, 1, 15))
uncle_bob.save() # bob is now stored in the database
Probably after converting dict to model you need to call .save()
method