3

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

3 Answers 3

8

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))
Sign up to request clarification or add additional context in comments.

2 Comments

Isn't there any other way than using Q object's OR expression. I meant I have around 10 other criteria other than prefered_state so I felt it would be better If I could simply use any function OR something like that where I could simply mention I also want to include Null result for each criteria. Thanks anyway
@PointNetworks, write own function that creates filter for you from Qs. Q is the bottom of abstractions for django ORM.
1

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

Comments

0
from django.db.models import Q

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.