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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With