Combine model data with list of objects
I have a list of objects :
film_hc = [{'count': 2, 'pk': '33'},
{'count': 1, 'pk': '37'},
{'count': 1, 'pk': '49'}]
The 'pk' value is the primary key for a record in a model. I would like to add the name field of that record to this list of objects. To get one name, I can use:
record = Film.objects.get(pk = film_hc[0]['pk'])
record.name
In the end, I would like to have something like this:
film_hc = [{'count': 2, 'pk': '33', 'name': 'name1'},
{'count': 1, 'pk': '37', 'name': 'name2'},
{'count': 1, 'pk': '49', 'name': 'name3'}]
Question: What is the most efficient way to attach the necessary data to this preexisting list?
I am th开发者_StackOverflow社区inking I could use the zip function:
film_hc_with_names = zip(????, film_hc)
The problem is I'm not sure what I would substitute in place of those ???? to get the object then the name for each object in the list. Should I use a for loop instead? What is the most preferable option?
To avoid hitting the database multiple times, I recommend you use the in_bulk
queryset method. This takes a list of IDs, and returns a dictionary of ID mapped to model instance. So what you need to do is to run through your list of dictionaries first to extract the ID values, then do the query, then run through again to get the name for each instance. Even though this is doing two extra iterations, it should still be quicker than running multiple DB queries (although as always you should profile to make sure).
id_list = [film['id'] for film in film_hc]
objects = Film.objects.only('name').in_bulk(id_list)
for film in film_hc:
film['name'] = objects[film['id']].name
精彩评论