I have a typical Relational Database model laid out in Django where a typical model contains some I want to save data that I am receiving in JSON format (not flat) from an external api. I wan't it such that data gets saved to respective tables (not the whole json string to one field). What is the most clean and simple approach to do this? Is there a library available to make this task simpler? Here's an example to clarify my question, Models-
now, I typically have to save json string data that I obtain from an external api (secret ninja api) into this model, json looks like this JSON-
now logic for handling a typical ManyToManyField is fairly simple, logic code -
There are many approaches that i could use,
I would like to know if there is a single most obvious way to save data in this json form to database without coding the above logic multiple times, what would be the most elegant approach that you would suggest? Thanks all for reading the long post, | |||||||||||||||||
|
In my opinion the cleanest place for the code you need is as a new Manager method (eg from_json_string) on a custom manager for the NinjaData model. I don't think you should override the standard create, get_or_create etc methods since you're doing something a bit different from what they normally do and it's good to keep them working normally. Update:I realised I'd probably want this for myself at some point so I have coded up and lightly tested a generic function. Since it recursively goes through and affects other models I'm no longer certain it belongs as a Manager method and should probably be a stand-alone helper function. | |||||||||||||||||||||
|
I don't know if you're familiar with the terminology, but what you're basically trying to do is de-serialize from a serialized/string format (in this case, JSON) into Python model objects. I'm not familiar with Python libraries for doing this with JSON, so I can't recommend/endorse any, but a search using terms like "python", "deserialization", "json", "object", and "graph" seems to reveal some Django documentation for serialization and the library jsonpickle on github. | |||||||||||||
|