Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Query results as 'associative' dict?

I was wondering if there was any handy helpers in Django which would return the results of a query into a more 'usuable' format so I don't have to iterate through them in my view.

I have a query like this:

self.filter(key__in=keys).values('key','value')

What I want to end up is an object which looks like

{'some_key':'some value', 'some_other_key':'some_other_value'}

So in my model I could do something like this:

settings = Setting.objects.get_keys(['some_setting','some_other_setting'])
print settings.some_setting # returns 'some value'

Where 'get_keys' is a manager function which runs the above filter query. Any idea how I might do this? I wouldn't be opposed to iterating through the results in the Settings Manager because I could store them for later... I couldn't quite figure our how to create a 'global' model variable though.

Any help would be greatly appreciated!

like image 247
Hanpan Avatar asked Jan 24 '11 11:01

Hanpan


2 Answers

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'))
like image 75
Daniel Roseman Avatar answered Oct 21 '22 06:10

Daniel Roseman


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?

like image 45
Exelian Avatar answered Oct 21 '22 04:10

Exelian