【问题标题】:Filter in django with or condition [duplicate]使用或条件过滤django [重复]
【发布时间】:2017-02-13 17:53:15
【问题描述】:

我想在过滤对象数据时在 django 中使用带有OR 条件的过滤器。

我有一个类的对象,并且我有 3 或 4 个字段,我想在此基础上在 Django 中使用 OR 条件过滤数据。

例如。

Obj = Books.objects.filter(title=title or price=price or description=description or author=author)

我认为这不是执行过滤的正确方法。

在我的 django 过滤器中使用OR 条件的正确方法是什么

【问题讨论】:

    标签: python django


    【解决方案1】:
    from django.db.models import Q
    
    Obj = Books.objects.filter(Q(title=title) | Q(price=price) | Q(description=description) | Q(author=author))
    

    文档:http://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects 来源:https://stackoverflow.com/a/739922/4808939

    【讨论】:

    • 如果我通过了所有归档,这将起作用。如果我通过一两个,它会给我以下错误Cannot use None as a query value
    • 在上面的示例代码中,如果我只传递标题,它会给我错误不能使用无作为查询值
    • @vikrant 你想允许空白查询值吗?如果是这样,您应该在将它们传递给 Q 对象之前对其进行消毒。像这样:title = title or ""。如果它是None,这将用空字符串替换该值。如果你不关心空白值,那么你应该有条件地构建你的 OR'ed together 查询。
    猜你喜欢
    • 2023-03-18
    • 2019-10-30
    • 1970-01-01
    • 2023-01-24
    • 2018-11-12
    • 2016-04-22
    • 1970-01-01
    • 2017-03-27
    • 2017-07-25
    相关资源
    最近更新 更多