Django模型查询中的OR运算符

时间:2011-03-26 20:42:58

标签: django django-models django-queryset

我正在尝试在Django OR函数中使用filter()运算符。现在我有

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

但我也希望按名字搜索。例如:

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

有谁知道怎么做?

2 个答案:

答案 0 :(得分:88)

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']))

答案 1 :(得分:10)

result = Contact.objects.filter(last_name__icontains=request.POST['query']) | Contact.objects.filter(first_name__icontains=request.POST['query'])