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
To get a map of all of the instances in a queryset into a single dictionary with a specified model field as the key, try 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
You want the in_bulk queryset method which, according to the docs:
Takes a list of field values (
id_list
) and thefield_name
for those values, and returns a dictionary mapping each value to an instance of the object with the given field value. Ifid_list
isn’t provided, all objects in the queryset are returned.field_name
must be a unique field, and it defaults to the primary key.
It takes a list of IDs, so you'll need to get that 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>}
Perhaps I'm missing something, but Django objects have a __dict__
attribute which seems be what you want.
dict((x.name, getattr(o, x.name)) for x in o._meta.fields)
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)
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...