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

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


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


This answer is late but could be helpful to a lot of guys out there.

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

This will generate something similar to

WHERE (hide=0 AND deleted=0 AND (T1.qty > 0 OR stock=0))


OK, no success here or on #django. So I choose to use a raw SQL query to solve this problem...

Here the working code:

types_list = Type.objects.raw('SELECT * FROM equipment_type    LEFT JOIN (                                                    SELECT type_id, SUM(quantity) AS qty                       FROM equipment_item                                        GROUP BY type_id                                       ) T1                                                       ON id = T1.type_id                                         WHERE hide=0 AND deleted=0 AND (T1.qty > 0 OR stock=0)     ')