Django - 按"特定值或无"过滤

Gad*_*i A 11 django

我在数据对象中有一个字段,可以为null或设置为某个整数.我希望,给定一个整数,用该整数值或所有过滤所有对象:

MyElements.objects.all().filter(value__in=[myInt, None])
Run Code Online (Sandbox Code Playgroud)

但是,此行不适用于具有空值的元素.更确切地说:

MyElements.objects.all().filter(value__in=[None])
Run Code Online (Sandbox Code Playgroud)

没有回报.而

MyElements.objects.all().filter(value = None)
Run Code Online (Sandbox Code Playgroud)

返回null值元素.

如何正确地重写原始查询(涉及myInt)?

Kev*_*one 12

您可以使用允许您在Django查询集中组合多个子句的Q值.

您的查询集将类似于:

from django.db.models import Q
MyElements.objects.all().filter(Q(value=None) | Q(value=myInt))
Run Code Online (Sandbox Code Playgroud)


Luk*_*ara 5

您可以尝试OR语句:

from django.db.models import Q
MyElements.objects.filter(Q(value__isnull=True) | Q(value=myInt))
Run Code Online (Sandbox Code Playgroud)

django文档