Point Networks
Point Networks

Reputation: 1101

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

Upvotes: 3

Views: 1815

Answers (3)

Anoop
Anoop

Reputation: 2798

from django.db.models import Q

result= Students.object.filter(Q(prefered_state='California')|Q(prefered_state__is_null=True))

Upvotes: 0

gtlambert
gtlambert

Reputation: 11961

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))

Upvotes: 8

Paritosh Gupta
Paritosh Gupta

Reputation: 326

result= Students.object.filter(Q(prefered_state='California') | Q(prefered_state__isnull=True))

Check out Q object here: https://docs.djangoproject.com/es/1.9/topics/db/queries/#complex-lookups-with-q-objects

Upvotes: 1

Related Questions