OR operator in Django model queries

2019-01-23 22:59发布

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?

2条回答
Evening l夕情丶
2楼-- · 2019-01-23 23:16

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']))
查看更多
干净又极端
3楼-- · 2019-01-23 23:25
result = Contact.objects.filter(last_name__icontains=request.POST['query']) | Contact.objects.filter(first_name__icontains=request.POST['query'])
查看更多
登录 后发表回答