Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get dict of model objects keyed by field

Assuming I have Django model called 'Blog' with a primary key field 'id', is there a query I can run that will return a dictionary with keys of the id values indexing the Blog model instances?

in_bulk() seems like the kind of thing I want, but it requires a list of the specific id values in this case, e.g.

Blog.objects.in_bulk([1])

will give

{1: <Blog: Beatles Blog>}

The document says that if you pass an empty list you'll get an empty dictionary back, so is there any way I can get all values back?

like image 440
Alb Avatar asked Nov 06 '13 20:11

Alb


1 Answers

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

like image 146
Basalex Avatar answered Sep 22 '22 18:09

Basalex