50

I'm trying to use an OR operator in the Django filter() function. Right now I have

contactlist = Contact.objects.filter(last_name__icontains=request.POST['query'])

but I also want to search by first name as well. For example:

contactlist = Contact.objects.filter(last_name__icontains=request.POST['query'] OR first_name__icontains=request.POST['query'])

Does anyone know how to do this?

Kevin Brown-Silva
  • 40,873
  • 40
  • 203
  • 237
Adam
  • 3,063
  • 5
  • 35
  • 49
  • 1
    possible duplicate of [Django Filters - or?](http://stackoverflow.com/questions/739776/django-filters-or) – e100 Mar 26 '15 at 17:46

2 Answers2

125

Q objects

from django.db.models import Q

Contact.objects.filter(Q(last_name__icontains=request.POST['query']) | 
                               Q(first_name__icontains=request.POST['query']))
Darian Moody
  • 3,565
  • 1
  • 22
  • 33
Yuji 'Tomita' Tomita
  • 115,817
  • 29
  • 282
  • 245
13
result = Contact.objects.filter(last_name__icontains=request.POST['query']) | Contact.objects.filter(first_name__icontains=request.POST['query'])
Eric
  • 147
  • 1
  • 3