JD Solanki
JD Solanki

Reputation: 998

Django - How to check if django is hitting database for certain query

I want to optimize the django app and for this I would like to know How can I check if my query is hitting database or I am getting result/return value from cached version?

For example:

products = Products.objects.filter(product_name__icontains="natural")

if not products.exist():
    return Response(...)

total_products = products.count()
first_product = product.first()

I like to execute this in shell and want to check which line hits the database and which one just return result from cached version so I can write optimized queries in my view.

I know about django-toolbar but I couldn't find if it supports things like this(does certain line hit database or result is from cached version).

Upvotes: 10

Views: 5279

Answers (2)

Smit Vekariya
Smit Vekariya

Reputation: 1

Use this decorator to find how many query hit database and total time of execution function

from django.db import connection
import time


@query_debugger
def test():
    pass



def query_debugger(view):
 def wrap(self, request, *args, **kwargs):
    initial_queries = len(connection.queries)
    start = time.time()
    result = view(self, request, *args, **kwargs)
    execution_time = time.time()-start
    final_queries = len(connection.queries)
    total_time = 0.0

    print(f"==============> function : {view.__name__} made {final_queries - initial_queries} queries <========================")
    for data in connection.queries:
        print(f"\n({data['time']}) => {data['sql']}")
        total_time += float(data['time'])
    print(f"\n===============> Total : {total_time}(query), {round(execution_time,3)}(function) <==================\n")

    return result
 return wrap

Upvotes: 0

JPG
JPG

Reputation: 88509

Check the lenth of connection.queries in this way,

from django.conf import settings
settings.DEBUG = True
from django.db import connection
print(len(connection.queries))

# do something with the database
products = Products.objects.filter(product_name__icontains="natural")
print(len(connection.queries))

# and execute the print statement again and again
total_products = products.count()
print(len(connection.queries))


first_product = product.first()
print(len(connection.queries))

Reference:

  1. Get SQL query count during a Django shell session

Upvotes: 24

Related Questions