有没有办法在过滤值列表时包含 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 block 来检查值列表中的 None 并在需要时使用 Q 对象构造查询,但是对于大量过滤器这样做会变得一团糟。一定有更好的方法,对吧?
最佳答案
我认为你需要使用 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()
不确定是否有更好的方法。
关于python - 可能包含 None 的 Django 过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44188325/