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

前端 未结 12 1287
野的像风
野的像风 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
    
    0 讨论(0)
  • 2020-11-30 17:43

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

    Takes a list of field values (id_list) and the field_name for those values, and returns a dictionary mapping each value to an instance of the object with the given field value. If id_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>}
    
    0 讨论(0)
  • 2020-11-30 17:45

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

    0 讨论(0)
  • 2020-11-30 17:47

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

    0 讨论(0)
  • 2020-11-30 17:50

    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 讨论(0)
  • 2020-11-30 17:51

    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...

    0 讨论(0)
提交回复
热议问题