Django通过多个过滤器进行过滤,检查某些条件

时间:2018-09-13 06:31:44

标签: python django django-queryset

我需要检查许多条件,并进行过滤或搜索是否指定了条件。我正在这样做,如下所示:

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合并为一个块:

方法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

然后我尝试了这个:

方法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

我尝试过的两种方法有什么问题?您能建议一个简约的解决方案吗?

1 个答案:

答案 0 :(得分:1)

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