Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter by id for multiple data in Django

Tags:

python

django

id_tuple= (1,3,4,5,7,9)
students =Students.objects.filter(id in id_tuple)

for s in students :
s.name='_new_name_'

This code is giving error ! How can i solve it ?? based on the above tuple i want to get all student !

How to do that

like image 924
Abhilash Joseph Avatar asked Mar 22 '12 12:03

Abhilash Joseph


2 Answers

As stepnak stated to do an in query the correct syntax is filter(id__in=id_tuple)

Django documentation would have been a great resource to get this information. https://docs.djangoproject.com/en/dev/ref/models/querysets/#in

like image 131
dm03514 Avatar answered Sep 20 '22 22:09

dm03514


You can use the IN field lookup as @stepank suggests.

A little more explanation: Django ORM uses a special syntax to translate python code to SQL statements. And simply passing a bool (if id is defined) value to filter is not valid syntax.

If you are new to Django, you can get started from here. You can also refer to the complete reference. Referring to documentation before asking is a good practice. :)

like image 32
kavinyao Avatar answered Sep 19 '22 22:09

kavinyao