这是我的django观点:
def get_initial_queryset(self):
filter_dict={}
location=self.request.POST.get('location_id')
if location:
set_if_not_none(filter_dict, 'port__device__host__location', location)
client=self.request.POST.get('client')
if client:
set_if_not_none(filter_dict, 'client__icontains', client)
phone=self.request.POST.get('phone')
if phone:
set_if_not_none(filter_dict, 'phone__icontains', phone)
if line:
set_if_not_none(filter_dict, 'line__icontains', phone)
return Client.objects.filter(**filter_dict)
这里我需要使用OR条件进行过滤,例如where phone like %phone% or line like %phone%
我怎么能用过滤器来做呢?
答案 0 :(得分:3)
见Complex queries with Q
objects。你需要写一些类似的东西:
from django.db.models import Q
Client.objects.filter(Q(phone__icontains=phone) | Q(line__icontains=phone))
您也可以像这样建立Q对象:
filter = Q()
location = self.request.POST.get('location_id')
if location:
filter = filter & Q(port__device__host__location=location)
client = self.request.POST.get('client')
if client:
filter = filter & Q(client__icontains=client)
phone = self.request.POST.get('phone')
if phone:
filter = filter & (Q(phone__icontains=phone) | Q(line__icontains=phone))
return Client.objects.filter(filter)