【问题标题】:Exclude two conditions in query via Django ORM通过 Django ORM 在查询中排除两个条件
【发布时间】:2014-10-25 12:21:48
【问题描述】:

如何通过逻辑 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')

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

【问题讨论】:

    标签: python mysql django


    【解决方案1】:

    您可以尝试使用“列表”。在状态列表中,您可以添加您想要的所有单词。

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

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

    【讨论】:

      【解决方案2】:

      看看Q Objects
      您的查询将是:

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

      【讨论】:

        【解决方案3】:

        您可以考虑将exclude 调用链接在一起:

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

        这具有类似于or 运算符的效果,并且比使用Q() 对象更具可读性。

        上述 Marcos 的“列表”方法可能最适合您的情况,但如果您在不同领域进行“或-ing”,我的方法会很有用:

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

        这将返回所有 Books 并排除由 Joe 创作,于 2018 年发布的那些。

        【讨论】:

          【解决方案4】:

          你可以用Q做到这一点

          from django.db.models import Q
          Model.objects.filter(country_send=country, ~Q(status__in=['deleted', ''])).order_by('-id')
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2015-10-26
            • 1970-01-01
            • 1970-01-01
            • 2021-12-20
            • 1970-01-01
            • 2014-05-27
            • 2016-04-22
            • 2020-12-26
            相关资源
            最近更新 更多