69👍
When you have list of items and you want to check the possible values from the list then you can’t use =
.
The sql query will be like SELECT * FROM mytable WHERE ids=[1, 3, 6, 7, 9]
which is not true. You have to use in
operator for this so you query will be like SELECT * FROM mytable WHERE ids in (1, 3, 6, 7, 9)
for that Django provide __in
operator.
- [Django]-How to force application version on AWS Elastic Beanstalk
- [Django]-Django py.test does not find settings module
- [Django]-How to combine django "prefetch_related" and "values" methods?
16👍
From the Django documentation:
Blog.objects.in_bulk([1])
{1: <Blog: Beatles Blog>}
Blog.objects.in_bulk([1, 2])
{1: <Blog: Beatles Blog>, 2: <Blog: Cheddar Talk>}
Blog.objects.in_bulk([])
{}
Blog.objects.in_bulk()
{1: <Blog: Beatles Blog>, 2: <Blog: Cheddar Talk>, 3: <Blog: Django Weblog>}
Blog.objects.in_bulk(['beatles_blog'], field_name='slug')
{'beatles_blog': <Blog: Beatles Blog>}
- [Django]-Django logging of custom management commands
- [Django]-Django content-type : how do I get an object?
- [Django]-Django get objects not referenced by foreign key
4👍
You can do like this.
Blog.objects.filter(pk__in=[1, 4, 7])
But you should be careful. If just one element in the list is No-integer it doesn’t work.
For example this is an Exception.
Blog.objects.filter(pk__in=[1, 4, 'aa', 7])
- [Django]-Remove Labels in a Django Crispy Forms
- [Django]-Error: could not determine PostgreSQL version from '10.3' – Django on Heroku
- [Django]-Uwsgi installation error in windows 7
Source:stackexchange.com