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

Accepted answer
Score: 214

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

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

You are looking for the Values member of QuerySet which allows you 7 to get a list of dictionaries from your 6 query

Returns a ValuesQuerySet -- a QuerySet that 5 evaluates to a list of dictionaries instead 4 of model-instance objects. Each of those 3 dictionaries represents an object, with 2 the keys corresponding to the attribute 1 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'}]
Score: 19

Does this need to create an actual dict? could 3 you get by with only something that looked 2 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 1 in this way:

modelDict = DictModelAdaptor(DictModel)
modelDict["name"] = "Bob Jones"

etc...

Score: 17

You want the in_bulk queryset method which, according 9 to the docs:

Takes a list of field values 8 (id_list) and the field_name for those values, and returns 7 a dictionary mapping each value to an instance 6 of the object with the given field value. If 5 id_list isn’t provided, all objects in the queryset 4 are returned. field_name must be a unique field, and 3 it defaults to the primary key.

It takes 2 a list of IDs, so you'll need to get that 1 first via the values_list method:

ids = MyModel.objects.values_list('id', flat=True)
ids_to_model_instances = MyModel.objects.in_bulk(ids)
# {1: <MyModel: 1>, 2: <MyModel: 2>, 3: <MyModel: 3>}
Score: 14

You can use the python serializer:

from django.core import serializers
data = serializers.serialize('python', DictModel.objects.all())

0

Score: 7

use

dict(((m.key, m.value) for m in DictModel.objects.all())

As suggested by Tom Leys, we do not 4 need to get whole object, we can get only 3 those values we need e.g.

dict(((m['key'], m['value']) for m in DictModel.objects.values('key', 'value')))

and if you need 2 all values, it is better to keep whole object 1 in dict e.g.

dict(((m.key, m) for m in DictModel.objects.all())
Score: 6

dict((x.name, getattr(o, x.name)) for x in o._meta.fields)

0

Score: 4

Perhaps I'm missing something, but Django 2 objects have a __dict__ attribute which seems be 1 what you want.

Score: 2

To get values of a models into dictionary, add 3 below code at the place where u need that 2 dictionary

from models import DictModel

activity_map = dict(Plan.objects.values_list('key', 'value'))

activity_map is a dictionary which 1 contains required information .

Score: 2
user = mymodel.objects.all()
user.values() 

You can also try

user.values_list() # getting as list

0

Score: 1

Or were you trying to do something like:

def someview(req):
    models = MyModel.objects.all()
    toTuple = lambda field: (getattr(field, 'someatt'), getattr(field, 'someotheratt'))  
    data = dict(map(toTuple,models))
    return render_to_response(template, data)

0

Score: 1

To get a map of all of the instances in 3 a queryset into a single dictionary with 2 a specified model field as the key, try 1 doing this

from django.forms.models import model_to_dict
from myApp.models import myModel

allObjs = myModel.objects.all()
f = {}         # initialise the output
key = 'key'    # one of the fields from myModel

[f.update({x[key]: x}) for x in [model_to_dict(y) for y in allObjs]]
return f

More Related questions