gpt4 book ai didi

python - Django 通过多个过滤器过滤,检查某些条件

转载 作者:太空宇宙 更新时间:2023-11-04 04:33:10 25 4
gpt4 key购买 nike

我需要检查许多条件,如果指定了条件,则进行过滤或搜索。我这样做如下:

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(),
)

我试图将 if 和 else 组合成一个 block :

方法一:

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

然后我试了一下:

方法二:

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

我试过的两种方法有什么问题?你能推荐一个简约的解决方案吗?

最佳答案

在 python 中,您可以使用 None 关键字使变量不持有任何值。

对于合并,你可以这样去做:

my_q = or_q_if_truthfull(
name__lower__contains=name.lower(),
age=age if age.isdigit() else None,
mobile__contains=phone,
email__lower__contains=email.lower(),
address__lower__contains=address.lower(),
city__lower__contains=city.lower(),
)

关于python - Django 通过多个过滤器过滤,检查某些条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52307817/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com