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?

-------------Problems Reply------------

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


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.


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

Example 2 (chained)


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:

Book with

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

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

You can use the connection module to see the raw sql queries to compare. As explained by Yuji's, for the most part they are equivalent as shown here:

>>> from django.db import connection
>>> samples1 = Unit.objects.filter(color="orange", volume=None)
>>> samples2 = Unit.objects.filter(color="orange").filter(volume=None)
>>> list(samples1)
>>> list(samples2)
>>> for q in connection.queries:
... print q['sql']
SELECT `samples_unit`.`id`, `samples_unit`.`color`, `samples_unit`.`volume` FROM `samples_unit` WHERE (`samples_unit`.`color` = orange AND `samples_unit`.`volume` IS NULL)
SELECT `samples_unit`.`id`, `samples_unit`.`color`, `samples_unit`.`volume` FROM `samples_unit` WHERE (`samples_unit`.`color` = orange AND `samples_unit`.`volume` IS NULL)

Most of the time, there is only one possible set of results for a query.

The use for chaining filters comes when you are dealing with m2m:

Consider this:

# will return all Model with m2m field 1

# will return Model with both 1 AND 2

# this will NOT work
Model.objects.filter(Q(m2m_field=1) & Q(m2m_field=2))

Other examples are welcome.

The case in which results of "multiple arguments filter-query" is different then "chained-filter-query", following:

Selecting referenced objects on the basis of referencing objects and relationship is one-to-many (or many-to-many).

Multiple filters:

Referenced.filter(referencing1_a=x, referencing1_b=y)
# same referencing model ^^ ^^

Chained filters:


Both queries can output different result:
If more then one rows in referencing-modelReferencing1can refer to same row in referenced-modelReferenced. This can be the case in Referenced: Referencing1 have either 1:N (one to many) or N:M (many to many) relation-ship.


Consider my application my_company has two models Employee and Dependent. An employee in my_company can have more than dependents(in other-words a dependent can be son/daughter of a single employee, while a employee can have more than one son/daughter).
Ehh, assuming like husband-wife both can't work in a my_company. I took 1:m example

So, Employee is referenced-model that can be referenced by more then Dependent that is referencing-model. Now consider relation-state as follows:

Employee: Dependent:
+------+ +------+--------+-------------+--------------+
| name | | name | E-name | school_mark | college_mark |
+------+ +------+--------+-------------+--------------+
| A | | a1 | A | 79 | 81 |
| B | | b1 | B | 80 | 60 |
+------+ | b2 | B | 68 | 86 |

Dependenta1refers to employeeA, and dependentb1, b2references to employeeB.

Now my query is:

Find all employees those having son/daughter has distinction marks (say >= 75%) in both college and school?

>>> Employee.objects.filter(dependent__school_mark__gte=75,
... dependent__college_mark__gte=75)

[<Employee: A>]

Output is 'A' dependent 'a1' has distinction marks in both college and school is dependent on employee 'A'. Note 'B' is not selected because nether of 'B''s child has distinction marks in both college and school. Relational algebra:

Employee (school_mark >=75 AND college_mark>=75)Dependent

In Second, case I need a query:

Find all employees whose some of dependents has distinction marks in college and school?

>>> Employee.objects.filter(
... dependent__school_mark__gte=75
... ).filter(
... dependent__college_mark__gte=75)

[<Employee: A>, <Employee: B>]

This time 'B' also selected because 'B' has two children (more than one!), one has distinction mark in school 'b1' and other is has distinction mark in college 'b2'.
Order of filter doesn't matter we can also write above query as:

>>> Employee.objects.filter(
... dependent__college_mark__gte=75
... ).filter(
... dependent__school_mark__gte=75)

[<Employee: A>, <Employee: B>]

result is same! Relational algebra can be:

(Employee (school_mark >=75)Dependent) (college_mark>=75)Dependent

Note following:

dq1 = Dependent.objects.filter(college_mark__gte=75, school_mark__gte=75)
dq2 = Dependent.objects.filter(college_mark__gte=75).filter(school_mark__gte=75)

Outputs same result: [<Dependent: a1>]

I check target SQL query generated by Django using print qd1.query and print qd2.query both are same(Django 1.6).

But semantically both are different to me. first looks like simple section σ[school_mark >= 75 AND college_mark >= 75](Dependent) and second like slow nested query: σ[school_mark >= 75][college_mark >= 75](Dependent)).

If one need Code @codepad

btw, it is given in documentation @Spanning multi-valued relationships I have just added an example, I think it will be helpful for someone new.

There is a difference when you have request to your related object, for example

class Book(models.Model):
author = models.ForeignKey(Author)
name = models.ForeignKey(Region)

class Author(models.Model):
name = models.ForeignKey(Region)



returns empty set

and request


returns authors that have books with both 'name1' and 'name2'

for details look at https://docs.djangoproject.com/en/dev/topics/db/queries/#s-spanning-multi-valued-relationships

The performance difference is huge. Try it and see.


is surprisingly slow compared to

Model.objects.filter(condition_a, condition_b, condition_c)

As mentioned in "Effective Django ORM",

  • QuerySets maintain state in memory
  • Chaining triggers cloning, duplicating that state
  • Unfortunately, QuerySets maintain a lot of state
  • If possible, don’t chain more than one filter
Category:python Views:4 Time:2011-04-04

Related post

  • Django - how to use templatetags filter with multiple arguments 2009-05-22

    I have a few values that I would like to pass into a filter and get a URL out of it. In my template I have: {% if names %} {% for name in names %} <a href='{{name|slugify|add_args:"custid=name.id, sortid=2"}}'>{{name}}</a> {%if not forloo

  • How do I add multiple arguments to my custom template filter in a django template? 2009-01-07

    Here's my custom filter: from django import template register = template.Library() @register.filter def replace(value, cherche, remplacement): return value.replace(cherche, remplacement) and here are the ways I tried using it in my template file that

  • How do I call an Angular.js filter with multiple OR arguments? 2013-04-07

    I want to use the filter in angular and want to filter for multiple values, if it has either one of the values then it should be displayed. I have for example this structure: An object movie which has the property genres and I want to filter for Acti

  • scala lift - filterNot with multiple arguments 2012-02-20

    I have the following filter on a List: messages = messages.filterNot(m => m.room == room) What I'm trying to do is have multiple arguments so I can match all items that have the same room ID and the same data value, so something like: messages = m

  • echoing multiple arguments when output_buffering is on 2009-06-27

    One of Googles Let's make the internet faster talks included something about using echo with multiple arguments in PHP instead of using print or string concatenation. echo 'The ball is ', $color; Rather than either of these echo "The ball is $color";

  • JQuery chained filter dropdown 2010-04-07

    I'm trying to implement chained filter dropdown using just javascript - jquery. The solution I need is http://www.codeassembly.com/Simple-chained-combobox-plugin-for-jQuery. However I can't use this solution as it depends on a PHP file. Are there way

  • How to filter for multiple criteria in Excel? 2010-08-19

    I am trying to filter for multiple criteria, but I see that the "Filter" option only has 2 fields for "AND/OR" options. I have a column full of links. I want to extract all rows that contain these in it: .pdf .doc .docx .xls .xlsx .rtf .txt .csv .pps

  • Calling a method with multiple arguments 2011-11-04

    I am creating an application that needs to find out if the current date is in one of several date ranges, and depending on which one it is in, it needs to set an enum to a value. I have the following code, but I don't know how to call the function wi

  • Passing Multiple Arguments from Panels into Views ( Drupal) 2009-04-21

    Anyone knows how to pass multiple arguments from Panels into a view in Drupal 6? Edit: I know how to pass one argument from Panels into Views, but not multiple arguments. --------------Solutions------------- In the panels argument field, separate the

  • How do I pass multiple arguments to a ruby method as an array? 2009-05-06

    I have a method in a rails helper file like this def table_for(collection, *args) options = args.extract_options! ... end and I want to be able to call this method like this args = [:name, :description, :start_date, :end_date] table_for(@things, args

  • how to pass multiple arguments to onSuccess function in Prototype? 2009-07-24

    I am a beginner in using Prototype library. I want to know how we can pass multiple arguments to onSuccess/onFailure function in Prototype? For example:- new Ajax.Request('testurl',{ method: 'post', parameters: {param1:"A", param2:"B", param3:"C"}, o

  • is it possible to have multiple search condition in filter function in MDX 2009-08-26

    Can there be multiple search conditions in the "filter function" in mdx. If possible how do I put [Measures].[x] > 0 and [Measures].[y] = 0 in filter(set expression, search condition) --------------Solutions------------- yes, I found that it can b

  • Call function with multiple arguments 2009-12-10

    Can I call a function with multiple arguments in a convenient way in JavaScript? example: var fn = function() { console.log(arguments); } var args = [1,2,3]; fn(args); I need arguments to be [1,2,3] just like my Array. --------------Solutions--------

  • Accept multiple arguments in an AS3 method 2009-12-16

    How do I accept multiple arguments in a custom method? Like: Proxy(101, 2.02, "303"); function Proxy(args:Arguments){ Task(args); } function Task(var1:int, var2:Number, var3:String){ // work with vars } --------------Solutions------------- You wouldn

  • Multiple argument IF statement - T-SQL 2009-12-28

    How do I write an IF statement with multiple arguments in T-SQL? Current source error: DECLARE @StartDate AS DATETIME DECLARE @EndDate AS DATETIME SET @StartDate = NULL SET @EndDate = NULL IF (@StartDate IS NOT NULL AND @EndDate IS NOT NULL) BEGIN --

  • Passing multiple arguments to C function within Python 2010-01-28

    Let's say I have a c library that manipulates a world somehow. I want to use this library with python. I want to be able to write simple python scripts that represent different scenarios of world management. I have functions that create and destroy a

  • @selector - With Multiple Arguments? 2010-02-19

    I have been using @selector today for the first time and have not been able to work out how to do the following? How would you write the @selector if you had more than one argument? No arguments: -(void)printText { NSLog(@"Fish"); } [self performSele

  • Map applied to multiple arguments in Haskell 2010-03-01

    Is there a way to use Haskell's "map" or something similar with multiple arguments? i.e. to find the distance between a given point (defined as a tuple) and a list of other points: map distance (-3,-3) buildings Clearly, that doesn't work, because it

  • One constructor - multiple arguments 2010-03-03

    I've found a task on some Java programming competition. One must create class Sentence with only one argument 'text' and only one constructor. Here's sample test code : Sentence s1=new Sentence("only","CAT"), s2=new Sentence("and", 2, "mice"), s3=new

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.158 (s). 11 q(s)