I need to check for a number of conditions and do a filter OR search if the conditions are specified. I am doing it as below:
def or_q_if_truthfull(**kwargs):
filtered = [Q(**{k: v}) for k, v in kwargs.items() if v]
if filtered:
return reduce(or_,filtered)
else:
return Q()
def check():
if age.isdigit():
my_q = or_q_if_truthfull(
name__lower__contains=name.lower(),
age=age,
mobile__contains=phone,
email__lower__contains=email.lower(),
address__lower__contains=address.lower(),
city__lower__contains=city.lower(),
)
else:
my_q = or_q_if_truthfull(
name__lower__contains=name.lower(),
mobile__contains=phone,
email__lower__contains=email.lower(),
address__lower__contains=address.lower(),
city__lower__contains=city.lower(),
)
I tried to combine the if and else into one block:
Method 1:
my_q = or_q_if_truthfull(
name__lower__contains=name.lower(),
age=age if age.isdigit(),
mobile__contains=mobile,
alternate__contains=alternate,
email__lower__contains=email.lower() if email else email,
address__lower__contains=address.lower(),
city__lower__contains=city.lower(),
)
File "/home/joel/myappointments/clinic/views.py", line 97
age=age if age.isdigit(),
^
SyntaxError: invalid syntax
Then I tried this:
Method 2:
from numbers import Number
my_q = or_q_if_truthfull(
cstid=HospitalID,
name__lower__contains=name.lower() if name else name,
age=age if isinstance(age, Number),
mobile__contains=mobile,
alternate__contains=alternate,
email__lower__contains=email.lower() if email else email,
address__lower__contains=address.lower(),
city__lower__contains=city.lower(),
)
File "/home/joel/myappointments/clinic/views.py", line 97
age=age if isinstance(age, Number),
^
SyntaxError: invalid syntax
What's the issue in the two methods I tried? Can you suggest a minimalistic solution?