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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With