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 ther
You are looking for the Values member of QuerySet which allows you to get a list of dictionaries from your query
Returns a ValuesQuerySet -- a QuerySet that evaluates to a list of dictionaries instead of model-instance objects. Each of those dictionaries represents an object, with the keys corresponding to the attribute names of model objects.
>>> Blog.objects.values()
[{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}],
>>> Blog.objects.values('id', 'name')
[{'id': 1, 'name': 'Beatles Blog'}]
user = mymodel.objects.all()
user.values()
You can also try
user.values_list() # getting as list
To get values of a models into dictionary, add below code at the place where u need that dictionary
from models import DictModel
activity_map = dict(Plan.objects.values_list('key', 'value'))
activity_map is a dictionary which contains required information .
You can use the python
serializer:
from django.core import serializers
data = serializers.serialize('python', DictModel.objects.all())
You can also rely on django code already written ;).
from django.forms.models import model_to_dict
model_to_dict(instance, fields=[], exclude=[])
use
dict(((m.key, m.value) for m in DictModel.objects.all())
As suggested by Tom Leys, we do not need to get whole object, we can get only those values we need e.g.
dict(((m['key'], m['value']) for m in DictModel.objects.values('key', 'value')))
and if you need all values, it is better to keep whole object in dict e.g.
dict(((m.key, m) for m in DictModel.objects.all())