如何通过Django ORM在查询中排除两个条件?

26

如何通过逻辑 OR 来排除同时符合两个条件:

Object.objects.filter(country_send=country).exclude(status__exact='').order_by('-id')
Object.objects.filter(country_send=country).exclude(status__exact='deleted').order_by('-id')

我正在尝试排除没有状态和状态为“已删除”的对象。

4个回答

30

看一看 Q 对象
你的查询将是:

from django.db.models import Q
Object.objects.filter(country_send=country).exclude(Q(status__exact='') | Q(status__exact='deleted')).order_by('-id')

29
您可以尝试使用“列表”。在状态列表中,您可以添加所有想要的单词。
status = ['deleted', '']
Object.objects.filter(country_send=country).exclude(status__in=status).order_by('-id')

关于列表的更多信息:http://www.sthurlow.com/python/lesson06/


14

你可以考虑将exclude函数链接在一起使用:

Object.objects.filter(country_send=country).exclude(status='').exclude(status='deleted').order_by('-id')

这会起到像一个or运算符的作用,并且比使用Q()对象更易读。

马尔科斯上面提到的“列表”方法可能在您的情况下是最好的选择,但如果您正在不同字段上进行“或”操作,则我的方法将非常有用:

Book.objects.exclude(author='Joe').exclude(publish_year='2018')

这将返回所有Books,并排除由Joe撰写或在2018年出版的书。


3
你可以使用Q来实现。
from django.db.models import Q
Model.objects.filter(country_send=country, ~Q(status__in=['deleted', ''])).order_by('-id')

这段代码出现了语法错误:位置参数跟随关键字参数。 - Hamid Rasti

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接