Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OR operator in Django model queries

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?

like image 638
Adam Avatar asked Mar 26 '11 20:03

Adam


People also ask

What is and operator in Django?

& is a Binary AND Operator copies a bit to the result if it exists in both operands. and Called Logical AND operator. If both the operands are true then then condition becomes true.

What is Q expression in Django?

Q object encapsulates a SQL expression in a Python object that can be used in database-related operations. Using Q objects we can make complex queries with less and simple code. For example, this Q object filters whether the question starts wiht 'what': from django.

How do you use get and filter together in Django?

Basically use get() when you want to get a single unique object, and filter() when you want to get all objects that match your lookup parameters. Show activity on this post. Show activity on this post. Show activity on this post.


1 Answers

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'])) 
like image 111
Yuji 'Tomita' Tomita Avatar answered Sep 19 '22 21:09

Yuji 'Tomita' Tomita