Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - filtering by "certain value or None"

Tags:

django

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?

like image 592
Gadi A Avatar asked Dec 10 '13 08:12

Gadi A


1 Answers

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))
like image 144
Kevin Stone Avatar answered Oct 21 '22 04:10

Kevin Stone