Skip to content Skip to sidebar Skip to footer

Django Import/reformat Json Into Model

I like to periodically import json data into a Django. What's the best way to import the data below to a Django model. As far as I've seen is the best approach to use Django fixtur

Solution 1:

I wrote a simple script to parse the input file and generate a fixture:

import json
import copy

withopen('/tmp/data.json') as dataf, open('/tmp/output.json', 'w') asout:
    data = json.load(dataf)
    newdata = []
    for i, block inenumerate(data):
        new = dict(model="appname.Item", pk=block['id'])
        new['fields'] = dict(item_name=block['item']['item_type']['name'],
                             timestamp=block['timestamp'],
                             value01=block['itemdatavalues'][0]['value'],
                             value02=block['itemdatavalues'][1]['value'])
        newdata.append(copy.deepcopy(new))
    json.dump(newdata, out, indent=2)

Using your input, this results in:

[{"pk":1,"model":"appname.Item","fields":{"item_name":"Item1","timestamp":"2017-04-18 09:24:46","value01":"15.00","value02":"12.68"}},{"pk":2,"model":"appname.Item","fields":{"item_name":"Item1","timestamp":"2017-04-18 09:25:44","value01":"14.92","value02":"12.42"}}]

Which is suitable for use as a fixture. Obviously, you will have to fix the appname.

Solution 2:

This might help: https://docs.djangoproject.com/en/1.11/ref/models/instances/. You should be able to create a new model object in whatever methods you are receiving that json in, then parse whatever json values you want into the object. There are some pretty easy json libraries for python. That is, unless you are wanting to handle something differently, or I am reading the documentation wrong. Have a good day!

Post a Comment for "Django Import/reformat Json Into Model"