Ad
What Is The Performance Difference In The Following Two Cases Of Select_related
I have the following two cases. Of the two, I am not able to tell which is the best order to take. Is there a performance issue in either of them??
Case 1
Model.objects.filter(item1=4,item2=5).select_related('store').get(id=1)
Case 2
Model.objects.select_related('store').filter(item1=4,item2=5).get(id=1)
Ad
Answer
You can inspect the query that Django makes by looking at the connections.queries
list. So you can print the last query with:
>>> from django.db import connection
>>> print(connection.queries[-1]['sql'])
For the first query, we get:
>>> Model.objects.filter(item1=4,item2=5).select_related('store').get(id=1)
<Model: Model object (1)>
>>> print(connection.queries[-1]['sql'])
SELECT "app_name_model"."id", "app_name_model"."store_id", "app_name_model"."item1", "app_name_model"."item2", "app_name_store"."id" FROM "app_name_model" INNER JOIN "app_name_store" ON ("app_name_model"."store_id" = "app_name_store"."id") WHERE ("app_name_model"."item1" = 4 AND "app_name_model"."item2" = 5 AND "app_name_model"."id" = 1) LIMIT 21
whereas for the latter, it is:
>>> Model.objects.select_related('store').filter(item1=4,item2=5).get(id=1)
<Model: Model object (1)>
>>> print(connection.queries[-1]['sql'])
SELECT "app_name_model"."id", "app_name_model"."store_id", "app_name_model"."item1", "app_name_model"."item2", "app_name_store"."id" FROM "app_name_model" INNER JOIN "app_name_store" ON ("app_name_model"."store_id" = "app_name_store"."id") WHERE ("app_name_model"."item1" = 4 AND "app_name_model"."item2" = 5 AND "app_name_model"."id" = 1) LIMIT 21
Both produce thus exactly the same query:
SELECT "app_name_model"."id", "app_name_model"."store_id", "app_name_model"."item1", "app_name_model"."item2", "app_name_store"."id" FROM "app_name_model" INNER JOIN "app_name_store" ON ("app_name_model"."store_id" = "app_name_store"."id") WHERE ("app_name_model"."item1" = 4 AND "app_name_model"."item2" = 5 AND "app_name_model"."id" = 1)
Where the parts in boldface is the effect of the .select_related(…)
call [Django-doc].
Ad
source: stackoverflow.com
Related Questions
- → Django: Identify the urls that provide duplicate content and set a canonical link
- → How can I create two views function in a models Django
- → Pass url with id to html page that is called by another url
- → SuspiciousFileOperation at /index/
- → Sorting 10k data set to the dict by child basis
- → How to ADD for loop result in templates
- → Page not found (404) The current path, register/register, didn’t match any of these
- → How to reduce for loops in html in Django?
- → Display Todo under its category [Django]
- → How do you pass two parameters through url in django
- → TemplateSyntaxError during Template rendering
- → How to auto update data in django?
- → download django data model as csv
Ad