Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Model.objects.select_related('store').filter(item1=4,item2=5).get(id=1)

>Solution :

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].

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading