Django查询过滤参数及Q

Django query filter parameters and Q

我正在尝试使用一个参数进行 Django 查询过滤,并且还使用 "Q",如下所示:

            variables = Indicator.objects.filter(
                type = constants_type_indicator_variable.variable,
                        Q(current_state = constants_current_state.valid) | 
                        Q(current_state = constants_current_state.current_registered) | 
                        Q(current_state = constants_current_state.re_opened) | 
                        Q(current_state = constants_current_state.open_registered)
            )

但是我在第一行 "Q" 中收到此错误:

non-keyword arg after keyword arg

如果我只使用 "Q" 而不按 "type" 字段进行过滤,它可以工作,但总的来说它会崩溃...

知道为什么吗?提前致谢。

试试这个:

 variables = Indicator.objects.filter(

                    Q(current_state = constants_current_state.valid) | 
                    Q(current_state = constants_current_state.current_registered) | 
                    Q(current_state = constants_current_state.re_opened) | 
                    Q(current_state = constants_current_state.open_registered),
                    type = constants_type_indicator_variable.variable,
        )

该错误意味着您在非关键字之前传递了 kwargs,通常在 python 函数中,应首先传递非关键字参数,然后传递关键字参数。这适用于所有 python 函数。

这个post对关键字函数参数有很好的解释。

虽然@kt14 的回答是正确的,但我认为这可以通过使用 in 而不是 Q 分隔查询来简化。您可以定义一个有效状态列表并像这样传递它:

valid_states = [
    constants_current_state.valid,
    constants_current_state.current_registered,
    constants_current_state.re_opened,
    constants_current_state.open_registered
]

variables = Indicator.objects.filter(
    type=constants_type_indicator_variable.variable,
    current_state__in=valid_states
)