Search code examples
djangodjango-modelsdjango-filters

How do I filter for both a null and a specific value in the same field in Django?


So here's a field I have in one of my models:

year = models.ForeignKey(Year, blank=True, null=True)

Now I want to get all the objects of that model whose year field is either null or specific_year.

This is what I tried:

MyModel.objects.filter(year__isnull=True, year=specific_year)
MyModel.objects.filter(year__isnull=True).filter(year=specific_year)
MyModel.objects.filter(year__in=[specific_year, None])

but they all give me an empty result.

I am pretty new to Django, so maybe there is something I'm missing here, but I couldn't find an answer in the docs. So how can I filter for all the objects whose year field is either null or specific_year?


Solution

  • You can use Q objects for complex filtering

    from django.db.models import Q
    
    MyModel.objects.filter(Q(year__isnull=True) | Q(year=specific_year))
    

    By default, using , or nested filtering would yield an AND result, whereas you need an OR result, for which you can use Q