Django – Search/Filter with OR/AND operator

Simple object search with or operator in Django

from django.db.models import Q
from project.models import MyModel

results = MyModel.objects.all()
           .filter(Q(host_name__contains=' ') | Q(host_controller__contains=' '))

# For multiple filters apart from the OR condition, need to call a new .filter method
results = MyModels.objects.all()
          .filter(Q(status=InstallationStatus.EXPIRED) | Q(physical_status=PhysicalStatus.SHUTDOWN))

Another implementation but using AND this time:

criterion1 = Q(question__contains="software")
criterion2 = Q(question__contains="java")
q = Question.objects.filter(criterion1 & criterion2)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s