difference between filter with multiple arguments and chain filter in django

As you can see in the generated SQL statements the difference is not the “OR” as some may suspect. It is how the WHERE and JOIN is placed.

Example1 (same joined table): from https://docs.djangoproject.com/en/dev/topics/db/queries/#spanning-multi-valued-relationships

Blog.objects.filter(
       entry__headline__contains="Lennon", 
       entry__pub_date__year=2008)

This will give you all the Blogs that have one entry with both (entry__headline__contains="Lennon") AND (entry__pub_date__year=2008), which is what you would expect from this query.

Result:

Blog with {entry.headline: 'Life of Lennon', entry.pub_date: '2008'}

Example 2 (chained)

Blog.objects.filter(
       entry__headline__contains="Lennon"
           ).filter(
       entry__pub_date__year=2008)

This will cover all the results from Example 1, but it will generate slightly more result. Because it first filters all the blogs with (entry__headline__contains="Lennon") and then from the result filters (entry__pub_date__year=2008).

The difference is that it will also give you results like:

A single Blog with multiple entries

{entry.headline: '**Lennon**', entry.pub_date: 2000}, 
{entry.headline: 'Bill', entry.pub_date: **2008**}

When the first filter was evaluated the book is included because of the first entry (even though it has other entries that don’t match). When the second filter is evaluated the book is included because of the second entry.

One table: But if the query doesn’t involve joined tables like the example from Yuji and DTing. The result is same.

Leave a Comment