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

前端 未结 12 1317
野的像风
野的像风 2020-11-30 16:45

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

12条回答
  •  青春惊慌失措
    2020-11-30 17:36

    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
    

提交回复
热议问题