17

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?

Gadi A
  • 3,449
  • 8
  • 36
  • 54

2 Answers2

18

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))
Kevin Stone
  • 8,831
  • 41
  • 29
7

You can try OR statement:

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

django documentation

Lukasz Koziara
  • 4,274
  • 5
  • 32
  • 43