mehrdadep
mehrdadep

Reputation: 1019

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

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)

Upvotes: 2

Views: 238

Answers (1)

shafikshaon
shafikshaon

Reputation: 6404

You can try this

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

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

Upvotes: 1

Related Questions