我在这个线程中遇到了与 OP 相同的问题:Django - filtering by "certain value or None" :
I have a field in an data object that can be either null or set to some integer. I want, given an integer, to filter all the objects with that integer value OR none:
MyElements.objects.all().filter(value__in=[myInt, None]) # Query 1
However, this line does not work for elements with null value. More precisely:
MyElements.objects.all().filter(value__in=[None]) # Query 2
returns nothing. whereas
MyElements.objects.all().filter(value = None) # Query 3
returns the null-valued elements.
How can I rewrite the original query (which involves myInt) correctly?
我知道 OP 已经接受了一个答案,但我想知道为什么 查询 2
没有产生任何结果。
最佳答案
它是根据SQL规则来执行的。 NULL 值不是要比较的实际值。这是一个未知的值(value)。
在这里阅读更多相关信息:is null vs == null
在 Django 中,您可以像这样获取具有 NULL 值的记录:
MyElements.objects.filter(value__isnull = True)
因此您需要先过滤掉比较列表中的None
,然后自行将其添加到您的查询中。
from django.db.models import Q
MyElements.objects.filter(Q(value__in = [list_of_vals]) | Q(value__isnull = True))
关于python - Django:按[无,其他]中的值过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55339584/