Django query count in terminal for debugging

In this article, we'll use the django-querycount library to monitor database queries in Django applications. This debugging tool displays a detailed report of database query counts in the terminal, helping developers identify performance bottlenecks by tracking every database hit on model objects.

Installation

First, install the django-querycount package using pip ?

pip install django-querycount

Configuration

Add the QueryCountMiddleware to your Django project's middleware in settings.py ?

MIDDLEWARE += [
    'querycount.middleware.QueryCountMiddleware',
]

This middleware will automatically monitor all database queries when DEBUG = True in your Django settings.

How It Works

The django-querycount library provides the following features ?

  • Query Tracking − Monitors both read and write operations on database models
  • Response Time − Calculates request and response processing times
  • Tabular Report − Displays organized query statistics in the terminal
  • Debug Mode Only − Only functions when DEBUG = True for security

Example Output

When you make requests to your Django application, you'll see output similar to this in your terminal ?

Django Query Count Report Model Queries Time (ms) Type User 3 15.2 SELECT Product 1 8.7 SELECT Order 2 12.1 INSERT Total Queries: 6 Total Time: 36.0ms

Key Features

Feature Description Benefit
Query Count Shows number of database queries per model Identify N+1 query problems
Response Time Measures query execution time Find slow database operations
Operation Type Shows SELECT, INSERT, UPDATE, DELETE Understand query patterns

Best Practices

When using django-querycount for debugging ?

  • Only enable in development environments with DEBUG = True
  • Monitor for excessive query counts that indicate N+1 problems
  • Use select_related() and prefetch_related() to optimize queries
  • Remove the middleware in production for security and performance

Conclusion

Django-querycount is an essential debugging tool that provides real-time database query monitoring in your terminal. It helps identify performance issues by showing query counts, execution times, and operation types for each database interaction.

Updated on: 2026-03-26T00:37:31+05:30

829 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements