Convert Django Model Instances To Dictionaries

I just searched for a method to convert a model instance to a dictionary in Django and the top few results were a bunch of custom methods in Django Snippets and Stack Overflow.  I was about to use one of those when I clicked on one last link that showed me a better solution.  There is a method already built into Django that does exactly what I want: django.forms.models.model_to_dict.

As I pointed that out to a coworker, he showed me that that's basically the same output as the .values() method in the queryset api.  If you don't specify a value to retrieve, it will retrieve the whole model instance as a dictionary.

Here's the output of these two pieces of code:

>>> Q.objects.filter(id=6).values()
[{'short': u'oui', 'deleted': False, 'language_id': 3L, 'long': u'oui', 'place_holder': u'oui', 'id': 6L, 'question_id': 8L}]
>>> model_to_dict(Q.objects.filter(id=6)[0])
{'short': u'oui', 'language': 3L, 'deleted': False, 'question': 8L, 'long': u'oui', 'place_holder': u'oui'}

There are two differences here, and one of them is pretty important.  First, .values() turns a queryset into an iterable that yields dictionaries, and model_to_dict turns a model instance into a single dictionary.  As long as you know about it this is pretty trivial to overcome.  Second, .values() converts foreign keys to {'_id': #} and model_to_dict converts them to {'': #}.  Since my purpose in using this was to populate a form I had to convert the id's into model instances and update the dictionary.  Not a big problem, but a bigger annoyance to solve than the first difference.


ray: Thanks for this. Saved me a lot of work I was about to get into.

jorgwel: Hi, thaks for this info. Another difference between the two ways you mention, is that “model_to_dict” do returns details about ManyToMany fields, and “.values()” doesn't.

Vinay Kotian: Hello, Thank you for the solution which has indeed helped. But now I am in a situation where i need all the dictionary from the queryset to be converted to string form rather than in unicode format({u'abc': #}). Please let me know a solution thank you.

tsaylor: You should use the json library to convert your dictionary to a json string.