Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django Assign json to model object

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):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{'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?

>Solution :

This should work:

for key, value in json_values.items():
    setattr(model, key, value)
model.save()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading