Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
291 views
in Technique[技术] by (71.8m points)

python - Django: Converting an entire set of a Model's objects into a single dictionary

If you came here from Google looking for model to dict, skip my question, and just jump down to the first answer. My question will only confuse you.

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 }}

With a result of DictModel.objects.get(key__exact=exampleKey).value

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can also rely on django code already written ;).

from django.forms.models import model_to_dict
model_to_dict(instance, fields=[], exclude=[])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...