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
- How can I filter Emoji characters from my input so I can save in MySQL <5.5?
- Celery beat not picking up periodic tasks
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)
- Tag inside tag in django template
- Django-registration, template
- Django – filtering by "certain value or None"
Source:stackexchange.com