I have a Django query that fetches from MyModel
based on certain conditions:
if beta:
MyModel.object.filter(x=alpha, y=beta)
else:
MyModel.object.filter(x=alpha)
Is it possible to eliminate the if beta:
check and do it in a single line i.e. make the query filter on y
only when beta
is not None
Is this a good (Djangonic) way:
MyModel.object.filter(**{'x':alpha, 'b':beta} if beta else **{'x':alpha})
Or is it possible to do something like this (I know the following is wrong, but can it be fixed to give the correct meaning?):
MyModel.object.filter(Q('x'=alpha) & (beta && Q('y'=beta)))