0

Im trying to make a django query filtering with one parameter and also using "Q" like this :

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

But im getting this error in the first "Q" line :

non-keyword arg after keyword arg

If i only use the "Q" without filtering by that "type" field it works, but togheter it crashes...

Any idea why ?, thanks in advance.

jsanchezs
  • 1,992
  • 3
  • 25
  • 51

2 Answers2

1

Try this:

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

That error means you have passed kwargs before the non-keyword, generally in python functions non-keywords arguments should be passed first and then keyword args. This applies for all the python functions.

This post has a good explanation about the keyword functional arguments.

Community
  • 1
  • 1
kt14
  • 838
  • 15
  • 25
1

While @kt14 's answer was correct, I think this could be simplified by use of in instead of Q separated queries. You could define a list of valid states and pass it in like so:

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
)
aredzko
  • 1,690
  • 14
  • 14