【问题标题】:Django filter which may include None可能包含无的 Django 过滤器
【发布时间】:2017-10-26 13:34:25
【问题描述】:

在对值列表进行过滤时,是否可以包含 None?

>>> MyModel.objects.filter(amount=10).count()
9
>>> MyModel.objects.filter(amount=None).count()
30
>>> MyModel.objects.filter(amount__in=[10]).count()
9
>>> MyModel.objects.filter(amount__in=[None, 10]).count()
9

我希望最后一次调用返回 39,而不是 9。

在我的实际用例中,None 可能包含也可能不包含在要过滤的值列表中。我可以使用 if/else 块来检查值列表中的 None 并在需要时使用 Q 对象构造查询,但是对于大量过滤器这样做会很麻烦。一定有更好的办法吧?

【问题讨论】:

    标签: python django python-3.x django-models


    【解决方案1】:

    我认为你需要使用 Q 对象,这样可能不会一团糟:

    MyModel.objects.filter(Q(amount__isnull=True) | Q(amount__in=the_list)).count()
    

    并且仅当None 在列表中时才包含第一部分...

    或者类似的东西:

    query = Q(amount__in=the_list)
    if None in the_list:
        query |= Q(amount__isnull=True)
    
    MyModel.objects.filter(query).count()
    

    不确定是否有更好的方法。

    【讨论】:

    • 我不知道|= 语法,所以至少这会有所帮助。
    • 有什么解释为什么 in 查找不适用于可迭代的 None 吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-06
    • 2019-01-20
    • 1970-01-01
    • 2011-01-01
    • 1970-01-01
    相关资源
    最近更新 更多