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!
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'))
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With