Django Model instanciation from json

60 Views Asked by At

I have downloaded data using manage.py dumpdata some_app.SomeModel > some_app_SomeModel.json for several models and am trying to programmatically load the files like so :

with open('some_app_SomeModel.json', encoding='utf-8') as data_file:
    json_data = json.loads(data_file.read())

    for model_data in json_data:
        model_data = model_data['fields']
        SomeModel.objects.create(**model_data)

Unfortunately this does not work for foreign key fields : the id value is not turned into the corresponding model instance and I get ValueError: Cannot assign "1": "SomeModel.fk_field" must be a "FK_Model" instance. where "1" is the json value of the fk field.

How to simply fix this ?

1

There are 1 best solutions below

3
willeM_ Van Onsem On BEST ANSWER

If fk_field, then you can assign to fk_field_id, hence you can rewrite this to:

with open('some_app_SomeModel.json', encoding='utf-8') as data_file:
    json_data = json.loads(data_file.read())

    for model_data in json_data:
        model_data = model_data['fields']
        model_data['fk_field_id'] = model_data.pop('fk_field')
        SomeModel.objects.create(**model_data)

Note that your items should contain a primary key, otherwise it is not said that these will link to the object with the primary key in the JSON file.