【问题标题】:Error on OR on filter Django过滤器 Django 上的 OR 错误
【发布时间】:2018-05-12 03:48:26
【问题描述】:

我正在尝试在 django 上创建或过滤器

这是我的小例子:

products=Products.objects.values('name', 'price').all().filter(status=1|0)

问题是不验证两个选项(1|0) 不要在打印时出现错误(products.query)只验证一个选项而不是 2 个选项..!!

谢谢!!

【问题讨论】:

  • all().filter() 是多余的
  • 为什么?也许你可以解释我这个..谢谢!
  • 下面查看my answer,我解释了

标签: django filter orm


【解决方案1】:

要在 django 中使用 OR 进行过滤,您需要一个名为 Q 的特殊类。 Documentation about Complex lookups with Q objects

from django.db.models import Q

products = Products.objects.values('name', 'price').filter(Q(status=1) | Q(status=0))

【讨论】:

    【解决方案2】:

    Q对象就好了

    manager.filter(Q(status=1) | Q(status=0))
    

    您需要知道管理器上的方法all() 只是委托给get_queryset()。 要使用filter(),您已经拥有QuerySet

    而不是调用查询集all(),然后是已经调用查询集的filter, 就做manager.filter()

    all().filter() 变成 filter() 因为它是多余的

    就是这样:

    from django.db.models import Q
    
    products = Product.objects.values('name','price').filter(
                     Q(status=1) | Q(status=0),
               )
    

    【讨论】:

    • 哦,谢谢,我想我需要阅读更多文档
    猜你喜欢
    • 2014-02-14
    • 2019-02-08
    • 2014-05-31
    • 2020-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-15
    • 2020-12-27
    相关资源
    最近更新 更多