Note that there are some explanatory texts on larger screens.

plurals
  1. PODjango: Converting an entire set of a Model's objects into a single dictionary
    text
    copied!<p><em>If you came here from Google looking for model to dict, skip my question, and just jump down to the first answer. My question will only confuse you.</em></p> <p>Is there a good way in Django to entire set of a Model's objects into a single dictionary? I mean, like this:</p> <pre><code>class DictModel(models.Model): key = models.CharField(20) value = models.CharField(200) DictModel.objects.all().to_dict() </code></pre> <p>... with the result being a dictionary with the key/value pairs made up of records in the Model? Has anyone else seen this as being useful for them?</p> <p>Thanks.<br /> <br /> <strong>Update</strong><br /> I just wanted to add is that my ultimate goal is to be able to do a simple variable lookup inside a Template. Something like:</p> <pre><code>{{ DictModel.exampleKey }} </code></pre> <p>With a result of DictModel.objects.get(key__exact=exampleKey).value</p> <p>Overall, though, you guys have really surprised me with how helpful allof your responses are, and how different the ways to approach it can be. Thanks a lot. <br /> <br /> <strong>Update October 2011:</strong> This question is the top result if you Google "django model_to_dict", which is actually pretty awful given that it solves a different problem than what I was asking.<br /> <br /> What I wanted was to be able to map all of the instances in a queryset into a single dictionary with a specified model field as the key.<br /> model_to_dict, on the other hand converts a single model instance into a dictionary.<br /> <br /> Now, my needs at the time were pretty darn specific, and probably extremely rare (I can't even remember the project I needed it for, or why). So I would be pretty surprised that anyone looking for information about model_to_dict is going to find my question actually useful. Sorry.<br /> <br /> model_to_dict seems to be a much more common usage case than I had. <br /> <br /> <strong>Update Dec 2011:</strong><br /> I changed the title to hopefully better reflect my original intent.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload