Django:将一整套Model对象转换为单个字典 [英] Django: Converting an entire set of a Model's objects into a single dictionary
问题描述
如果你从Google那里来寻找模型到dict,请跳过我的问题,然后再跳到第一个答案。我的问题只会让你感到困惑。
Django有没有一个很好的方式将一个Model的对象整套成单个字典?我的意思是这样:
Is there a good way in Django to entire set of a Model's objects into a single dictionary? I mean, like this:
class DictModel(models.Model):
key = models.CharField(20)
value = models.CharField(200)
DictModel.objects.all().to_dict()
...结果是一个字典,其中键/值对由模型中的记录组成?有没有人认为这对他们有用?
... with the result being a dictionary with the key/value pairs made up of records in the Model? Has anyone else seen this as being useful for them?
谢谢。
更新
我只是想添加的是,我的最终目标是能够在一个模板中做一个简单的变量查找。例如:
Thanks.
Update
I just wanted to add is that my ultimate goal is to be able to do a simple variable lookup inside a Template. Something like:
{{ DictModel.exampleKey }}
结果是DictModel.objects.get(key__exact = exampleKey).value
With a result of DictModel.objects.get(key__exact=exampleKey).value
总的来说,你们真正让我感到惊讶的是,你的回应是多么有用的,以及如何不同的方式来处理它。非常感谢。
2011年10月更新
如果您的Googledjango model_to_dict,这个问题是最高的结果,实际上很可怕,因为它解决了一个与我所要求的不同的问题。
我想要的是能够将查询中的所有实例映射到一个具有指定模型字段的单个字典作为关键字。
model_to_dict,另一方面将单个模型实例转换为字典。
现在,我当时的需求很具体,可能非常罕见(我甚至不记得我需要的项目,或者为什么)。所以我会非常惊讶,任何人寻找关于model_to_dict的信息将会发现我的问题实际上是有用的。对不起,
model_to_dict似乎比我更常见的使用案例。
2011年12月更新:
我更改了标题,希望更好地反映我的原意
Overall, though, you guys have really surprised me with how helpful allof your responses are, and how different the ways to approach it can be. Thanks a lot.
Update October 2011:
This question is the top result if you Google "django model_to_dict", which is actually pretty awful given that it solves a different problem than what I was asking.
What I wanted was to be able to map all of the instances in a queryset into a single dictionary with a specified model field as the key.
model_to_dict, on the other hand converts a single model instance into a dictionary.
Now, my needs at the time were pretty darn specific, and probably extremely rare (I can't even remember the project I needed it for, or why). So I would be pretty surprised that anyone looking for information about model_to_dict is going to find my question actually useful. Sorry.
model_to_dict seems to be a much more common usage case than I had.
Update Dec 2011:
I changed the title to hopefully better reflect my original intent.
推荐答案
这是否需要创建一个实际的字典?你可以得到只有一些看起来像一个dict的东西吗?
Does this need to create an actual dict? could you get by with only something that looked like a dict?
class DictModelAdaptor():
def __init__(self, model):
self.model = model
def __getitem__(self, key):
return self.model.objects.get(key=key)
def __setitem__(self, key, item):
pair = self.model()
pair.key = key
pair.value = item
pair.save()
def __contains__(self, key):
...
你可以这样包装一个模型:
You could then wrap a model in this way:
modelDict = DictModelAdaptor(DictModel)
modelDict["name"] = "Bob Jones"
等...
这篇关于Django:将一整套Model对象转换为单个字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!