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

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


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

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


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


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"

etc...