Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting JSON to model instance in Django

What's the best way in django to update a model instance given a json representation of that model instance.

Is using deserialize the correct approach? Are there tutorials available out there?

like image 205
9-bits Avatar asked Jul 14 '12 21:07

9-bits


1 Answers

The best approach would be to utilize one of the existing Django applications that support serializing model instances to and from JSON.

In either case, if you parse the JSON object to a Python dictionary, you can basically use the QuerySet.update() method directly.

So, say you get a dictionary where all the keys map to model attributes and they represent the values you'd want to update, you could do this:

updates = {                                    # Our parsed JSON data
    'pk': 1337,
    'foo': 'bar', 
    'baz': 192.05
}

id = updates.pop('pk')                         # Extract the instance's ID
Foo.objects.filter(id=id).update(**updates)    # Update the instance's data
like image 125
Filip Dupanović Avatar answered Sep 22 '22 23:09

Filip Dupanović