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 {‘<field_name>_id’: #} and model_to_dict converts them to {‘<field_name>’: #}.  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.

One thought on “Convert Django Model Instances To Dictionaries

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>