Django query filter combining AND and OR with Q objects don't return the expected results

前端 未结 4 1850
心在旅途
心在旅途 2021-02-05 01:51

I try to combine AND and OR in a filter using Q objects. It looks like that the | behave like an AND. This is related to the previous annotate which is run in the same query and

4条回答
  •  不思量自难忘°
    2021-02-05 02:05

    Try adding parentheses to explicitly specify your grouping? As you already figured out, multiple params to filter() are just joined via AND in the underlying SQL.

    Originally you had this for the filter:

    [...].filter(
        Q(hide=False) & Q(deleted=False),
        Q(stock=False) | Q(quantity__gte=1))
    

    If you wanted (A & B) & (C | D) then this should work:

    [...].filter(
        Q(hide=False) & Q(deleted=False) &
        (Q(stock=False) | Q(quantity__gte=1)))
    

提交回复
热议问题