Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to include null results in Django ORM queries

I am using Django ORM system. I have model of students where each student has his/her prefered state of work. Like few students wanna work in "Mahrashtra' State and others wanna work in some other state.

Let's suppose I wanna search for those students who have prefered working state as 'California'. I do following query

result= Students.object.filter(prefered_state='California')

and of course I get desired result but I wanna include even those students in results who haven't yet entered their preferred state. Means students with state as Null or ''. So isn't there any way to specify to include Null results for criteria other than using OR statement. As I have many more criteria for many other fields and I don't wanna include OR xyz is null for every field

like image 536
Point Networks Avatar asked Mar 03 '26 18:03

Point Networks


1 Answers

You could use Q. Note that this answer takes into account both NULL values and empty strings.

from django.db.models import Q

states = ['California', '']
Item.objects.filter(Q(prefered_state__in=states)|Q(prefered_state__isnull=True))
like image 174
gtlambert Avatar answered Mar 06 '26 07:03

gtlambert