Hanpan
Hanpan

Reputation: 10251

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!

Upvotes: 22

Views: 13348

Answers (2)

Exelian
Exelian

Reputation: 5888

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?

Upvotes: 7

Daniel Roseman
Daniel Roseman

Reputation: 599460

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'))

Upvotes: 42

Related Questions