[Fixed]-How to get dict of model objects keyed by field

21👍

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())

16👍

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

0👍

You can also try to put ValuesListQuerySet object in to “in_bulk” method like this:

blog_query = Blog.objects.values_list('pk', flat=True)
Blog.objects.in_bulk(blog_query)

Leave a comment