[Django]-Django – Query results as 'associative' dict?

42👍

If you use values_list rather than values, it will return a set of two-tuples, which you can then pass to dict() to create a dictionary:

return dict(self.filter(key__in=keys).values_list('key','value'))

7👍

I think what you’re looking for is: http://docs.djangoproject.com/en/stable/ref/models/querysets/#in-bulk
This function takes a list of primary keys and return a dictionary of the models mapped to the keys. It sounds like this is exactly what you want?

Leave a comment