Skip to main content

How to build your own DB queries tracking for Django?

What’s the ORM? It’s layer designed to help OOP developers interact with relational databases. Instead of write raw SQL every day, all you have to do is define a model and interact with the DB by writing code by Python.

  • Define a model
class Post(models.Model)
    id = models.BigAutoField(primary_key=True)
    slug = models.CharField(max_length=100)
    created_date = DateTimeField(auto_now_add=True)
  • Query the post that has “abc” slug
p = Post.objects.filter(slug="abc")

Well, writing less code is good. It speeds up development time for teams. But the hidden costs are great. It hides the developers from SQL so developers keep writing code without knowing the performance of their code. So let’s take time to write a simple code to show the hidden SQL :D

Django has its own DB hook, we use it.

  • The simple implementation that show the generated SQL
def execute_hook(execute, sql, params, many, context):
    try:
        return execute(sql, params, many, context)
    except Exception as e:
        raise
    finally:
        # Log your query here
        logger.info(f'SQL query = {sql}')
  • Django supports a local thread-safe context manager that when enters, install our hook, and when exits, remove it
from django.db import connection

def your_view(request):
    with connection.execute_wrapper(execute_hook):
        p = Post.objects.get(slug="abc")
        return Response(p)

Comments