Search code examples
pythondjangodjango-querysetdjango-orm

Filtering QuerySet in Djnago where a field has a specific value or is null


what's the right way to do this in Django, i want to to filter a queryset where the field has a specific value or is null,which means that if i filter a queryset by field named "type", it would return a queryset with objects has a specific value of type like "active" and also object with "type" has null value.


Solution

  • You can work with Q objects [Django-doc] for this:

    MyModel.objects.filter(
        Q(type='active') | Q(type=None)
    )

    Here we combine the two Q objects, which act as filters with a bitwise or operator |, and this means that we create a filter that acts as a logical or between the two filter conditions.