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?
& 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.
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.
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.
from django.db.models import Q Contact.objects.filter(Q(last_name__icontains=request.POST['query']) | Q(first_name__icontains=request.POST['query']))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With