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

Viewed 2492

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

Regards.

1 Answers

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
Related