I have this function:
# create a function to upload an object one to one given a json
def upload_object_values(model, json_values):
if json_values:
# the json values contain key value that match to the model
# use a copy to avoid runtime error dictionary changing size
for json_value in json_values.copy():
# remove all ids in model copy
if json_value[-3:] == '_id' or json_value == 'id':
json_values.pop(json_value)
# copy the object values only
# TODO: ASSIGN json_values to the model object
# save
# model.save()
sample json_values:
{'id': 1, 'notes': 'hello', 'name': 'world', 'phone': None, 'foreign_id': 2}
sample cleanedjson_values (removed id and foreign keys):
{'notes': 'hello', 'name': 'world', 'phone': None}
How do I assign these values to the model that I have with each key being a field with the same name in my model?
CodePudding user response:
This should work:
for key, value in json_values.items():
setattr(model, key, value)
model.save()