[Answered ]-Django Q&Q versus filter.filter

2👍

The difference is that the first query has two filter() calls, and the second query only has one.

The first query tries to find an object with a related item containing ‘Foo’ and a related item containing ‘Bar’. The second query tries to find an item with a single related item that contains both ‘Foo’ and ‘Bar’

The fact that one uses Q() objects is not significant – you could change the first query to:

Order.object.filter(
    Q(items__name__icontains="Foo"
).filter(
    Q(items__name__icontains="Bar")
)

However the Q() is required in your second Query 2m since it would be invalid Python to repeat the keyword argument in .filter(items__name__icontains="Foo", items__name__icontains="Bar")

See the docs on spanning multi-values relationships for more info.

Leave a comment