django-querycount
django-querycount is a Django middleware designed to provide real-time database query monitoring directly in the `runserver` console. It helps developers identify and optimize performance bottlenecks, such as N+1 query problems, by tracking the number of SQL queries executed for each request. This tool is specifically intended for development environments and is hardcoded to operate only when Django's `DEBUG` setting is `True`. The current version is 0.8.3, released in January 2023, and it remains an actively used utility in the Django community for performance debugging.
Warnings
- gotcha django-querycount is hardcoded to only run when Django's `DEBUG` setting is `True`. If `DEBUG` is `False`, the middleware will not activate and no query counts will be displayed.
- deprecated The old setting `QUERYCOUNT_THRESHOLDS` is still supported but is considered deprecated. The recommended way to configure thresholds and other options is via the `QUERYCOUNT` dictionary in your `settings.py`.
- gotcha This library is strictly for development and debugging. While it inherently only runs when `DEBUG=True`, ensure it is not relied upon or inadvertently left in production settings, as performance debugging tools can introduce overhead.
- gotcha Be aware of other similarly named packages, such as `django-query-counter`. `django-querycount` is specifically a middleware for console output, while `django-query-counter` provides decorators for views and management commands.
Install
-
pip install django-querycount
Imports
- QueryCountMiddleware
from querycount.middleware import QueryCountMiddleware
Quickstart
# myproject/settings.py
import os
# Ensure DEBUG is True for django-querycount to activate
DEBUG = os.environ.get('DJANGO_DEBUG', 'True').lower() == 'true'
INSTALLED_APPS = [
# ... your Django apps
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'querycount.middleware.QueryCountMiddleware', # Add this line
# ... other middleware
]
# Optional: Customize django-querycount settings
QUERYCOUNT = {
'THRESHOLDS': {
'MEDIUM': 50,
'HIGH': 200,
'MIN_TIME_TO_LOG': 0,
'MIN_QUERY_COUNT_TO_LOG': 0
},
'IGNORE_REQUEST_PATTERNS': [r'^/admin/'], # Example: Ignore admin requests
'DISPLAY_DUPLICATES': 5, # Display the 5 most duplicated queries
'RESPONSE_HEADER': 'X-DjangoQueryCount-Count' # Custom response header
}
# Other Django settings...