我试图使一个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函数中,非关键字参数应该先传递,然后才是关键字args。这适用于所有python函数。
这篇文章很好地解释了关键字函数参数
虽然@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
)