如何在 Django ORM 过滤器中使用 OR 条件? [复制]
Posted
技术标签:
【中文标题】如何在 Django ORM 过滤器中使用 OR 条件? [复制]【英文标题】:How can I use an OR-condition in a Django ORM filter? [duplicate] 【发布时间】:2016-05-26 01:48:47 【问题描述】:这是我的 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)
这里我需要用where phone like %phone% or line like %phone%
这样的OR条件进行过滤
如何使用过滤器做到这一点?
【问题讨论】:
【参考方案1】:见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)
【讨论】:
以上是关于如何在 Django ORM 过滤器中使用 OR 条件? [复制]的主要内容,如果未能解决你的问题,请参考以下文章