Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between filter with multiple arguments and chain filter in django

What is the difference between filter with multiple arguments and chain filter in django?

like image 734
testmobile Avatar asked Apr 04 '11 18:04

testmobile


People also ask

Can we use multiple filters in Django?

A QuerySet represents a collection of objects from your database. It can have zero, one or many filters. Filters narrow down the query results based on the given parameters. In SQL terms, a QuerySet equates to a SELECT statement, and a filter is a limiting clause such as WHERE or LIMIT .

What is the difference between filter and get method in Django?

Basically use get() when you want to get a single unique object, and filter() when you want to get all objects that match your lookup parameters.

What is the purpose of filter () method in Django?

The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.

How do I merge two QuerySets in Django?

Use union operator for queryset | to take union of two queryset. If both queryset belongs to same model / single model than it is possible to combine querysets by using union operator. One other way to achieve combine operation between two queryset is to use itertools chain function.


1 Answers

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.

like image 128
Johnny Tsang Avatar answered Oct 15 '22 11:10

Johnny Tsang