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(installation_type=InstallationTypes.EVAL)
          .filter(Q(status=InstallationStatus.EXPIRED) | Q(physical_status=PhysicalStatus.SHUTDOWN))
          .order_by('created_at')

Another implementation but using AND this time:

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

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

w

Connecting to %s