how to get dict of model objects keyed by field
The id_list
parameter of the in_bulk method is None
by default, so just don't pass anything to it:
>>> Blog.objects.in_bulk()
{1: <Blog: Beatles Blog>, 2: <Blog: Cheddar Talk>, 3: <Blog: Django Weblog>}
In the result, the default key is the primary key. To override that use:
Blog.objects.in_bulk(field_name='<unique_field_name>')
NOTE: the key must be unique or you will get ValueError
It's just python
{x.pk:x for x in Blog.objects.all()}
EDIT:
Alb here, just adding that if you're using Python 2.6 or earlier you need to use this older style syntax:
dict((x.pk, x) for x in Blog.objects.all())