Skip to main content
 首页 » 编程设计

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

2024年12月31日20mfryf

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

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