Include a condition only if the value is not None in django ORM

Viewed 78

I want to include a condition in django ORM's .objects.get method only if the value isn't None. Right now I'm using if/else and create two separate database query. Is it possible to combine these queries and do it at once?

What I'm doing:

if may_none_value:
    objects = MyModel.objects.get(field1=other_value, field2=may_none_value)
else:
    objects = MyModel.objects.get(field1=other_value)
1 Answers

You can try this

if may_none_value:
    conditions = {'field1': 'other_value'}
else:
    conditions = {}

objects = MyModel.objects.get(**conditions)
Related