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.
CodePudding user response:
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.
CodePudding user response:
There is a whole section in Django documentation related to model field lookups. But if you don't want to mess with it here is some examples:
# Obtaining all non-null fields
Model.objects.filter(some_field__isnull=False)
# Obtaining all rows with field value greater than some value
Model.objects.filter(some_field__isnull=False, some_field__gt=value)
# Actually the better way of writing complex queries is using Q objects
from django.db.models import Q
Model.objects.filter(Q(some_field__isnull=False) & Q(some_field__gt=value)) # The same thing as the previous example
# Using Q objects in this situation may seem useless and it kinda is, but as for me
# This improves readability of your query
There are a lot more things that you may want to do with your field, but I think that I described the most common use case.
Edit
As written in the Willem's answer to obtain rows that has value of "active" or null you should write such query:
Model.objects.filter(Q(type='active') | Q(type__isnull=True))
Hope that helps.