django-viewsdjango-select-related

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)

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