8

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?

2
  • Have you looked at this page on serialization of models in Django? Commented Jul 14, 2012 at 21:21
  • Yes - but i'm having difficulty with it. the json object i'm passing to the server doesn't have all the data in the model just a portion of it (including the pk of course). And I want to update the model based on that code. Commented Jul 14, 2012 at 21:28

1 Answer 1

13

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.