django-querycount

0.8.3 · active · verified Sat Apr 11

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

Install

Imports

Quickstart

To enable `django-querycount`, add `querycount.middleware.QueryCountMiddleware` to your `MIDDLEWARE` list in your Django project's `settings.py`. Ensure that `DEBUG = True` for `django-querycount` to function. You can also customize its behavior by defining a `QUERYCOUNT` dictionary in your settings.

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

view raw JSON →