I'm wondering if there is a way to conditionally filter a queryset in Django based on if the value filtered against is None
or not. I know that you can do something like this:
some_name = 'Bob'
qs = MyModel.objects.filter(gender='boy')
if some_name:
qs = qs.filter(name=some_name)
where we conditionally filter on the variable some_name
only if it exists. I'm curious if this logic can be replicated with a single query statement, instead of "chaining" on a filter to the end of a queryset. So this would look something like:
qs = MyModel.objects.filter(gender='boy').filter(name=some_name if some_name else None)
Obviously that example isn't valid, because it would filter on name=None instead of not filtering, but has anyone found a way to do what I'm intending? For longer, nested queries, it would be very helpful to have it all in one statement.