Django - 查询结果为“联想”字样? [英] Django - Query results as 'associative' dict?
问题描述
我想知道Django中是否有任何方便的帮助者可以将查询的结果返回到更可用的格式,因此我不必在我的视图中迭代。
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.
我有一个这样的查询:
self.filter(key__in=keys).values('key','value')
我想要结束的是一个看起来像/ p>
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'
其中'get_keys'是一个运行上述过滤器查询的管理器函数。有什么想法我该怎么做?我不会反对在设置管理器中迭代结果,因为我可以存储它们以供以后使用...我不太清楚如何创建一个全局模型变量。
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.
任何帮助将不胜感激!
推荐答案
如果您使用 values_list
而不是值
,它将返回一组两元组,然后您可以传递给 dict()
创建一个字典:
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'))
这篇关于Django - 查询结果为“联想”字样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!