Django - filtering by “certain value or None”

2020-08-12 09:00发布

问题:

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])

However, this line does not work for elements with null value. More precisely:

MyElements.objects.all().filter(value__in=[None])

returns nothing. whereas

MyElements.objects.all().filter(value = None)

returns the null-valued elements.

How can I rewrite the original query (which involves myInt) correctly?

回答1:

You can use Q values which allow you to combine multiple clauses in Django querysets.

Your query set would be something like:

from django.db.models import Q
MyElements.objects.all().filter(Q(value=None) | Q(value=myInt))


回答2:

You can try OR statement:

from django.db.models import Q
MyElements.objects.filter(Q(value__isnull=True) | Q(value=myInt))

django documentation



标签: django