Vasanth S
Vasanth S

Reputation: 94

Which is more efficient filter query in django and why?

1 : Model1.object.filter(column1="XYZ").filter(column2="ABC")

2 : Model1.object.filter(column1="XYX", column2="ABC")

Among these two, which is more efficient in terms of time taken as well as number of db calls?

Upvotes: 2

Views: 332

Answers (2)

j-i-l
j-i-l

Reputation: 10957

You can use the QuerySet API to see the actual sql query that are produced:

print(Model1.object.filter(column1="XYZ").filter(column2="ABC").query)

print(Model1.object.filter(column1="XYX", column2="ABC").query)

You'll find that the queries are the same.

Upvotes: 3

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476659

Among these two, which is more efficient in terms of time taken as well as number of db calls?

Both will produce the same query, unless column1 is a one-to-many or a many-to-many field, but then it is not a column of the model object. Both will produce a query that looks like:

SELECT appname_model1.*
FROM appname_model1
WHERE column1 = "XYZ" AND column2 = "ABC"

The second item will likely be slightly more efficient, since then it will evaluate two calls to the filter method, but this is only a matter of a few CPU cycles.

Upvotes: 3

Related Questions