How to View Raw SQL Queries in Django

Django ORM (Object-Relational Mapping) is powerful tool for managing your database interactions. However There are times when you need to inspect the raw SQL queries that Django generates to understand whats happening under the hood. In this blog post, we’ll explore how to see the raw SQL queries Django is running and provide examples with the expected output.

Enabling Query Logging

Django provides a straightforward way to enable query logging, allowing you to see the raw SQL queries generated by your application. You can enable query logging in your Django project’s settings.

Step 1: Open Your Settings – Navigate to your Django project’s settings file typically named settings.py.

Step 2: Configure Logging – Add the following configuration to enable query logging:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
    },
    'root': {
        'handlers': ['console'],
        'level': 'DEBUG',
    },
}

This configuration sets logging level to DEBUG and directs the logs to the console.

Step 3: Run Your Application – After updating your settings, run your Django application as you normally would.

Viewing Raw SQL Queries

Once query logging is enabled, you can view the raw SQL queries by accessing Django built-in django.db.connection object. Here how you can do it:

from django.db import connection

def view_raw_queries():
    # Run a query
    cursor = connection.cursor()
    cursor.execute('SELECT * FROM myapp_mymodel')

    # Fetch the raw SQL queries
    queries = connection.queries

    # Print the queries
    for query in queries:
        print(query['sql'])

view_raw_queries()

In this example, we first run a simple SQL query using the connection.cursor(). After executing the query, we retrieve the raw SQL queries from connection.queries and print each query to the console.

Expected Output

When you run the view_raw_queries() function, you’ll see the raw SQL queries generated by Django. Here’s an example of the expected output:

SELECT * FROM myapp_mymodel

The output will include all the SQL queries that Django generates during the execution of your application.

Enabling query logging in Django and viewing the raw SQL queries is valuable tool for understanding and optimizing your database interactions. By following the steps in this blog post, you can gain insights into how Django translates high-level queries into SQL statements and use this knowledge to enhance the performance and efficiency of your web applications.