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

前端 未结 12 1332
野的像风
野的像风 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: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: , 2: , 3: }
    

提交回复
热议问题