Created
January 29, 2026 13:21
-
-
Save archatas/1d58d642d05b422f08a6318ed6dbdad3 to your computer and use it in GitHub Desktop.
Django Database Query Analyzer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from django.db import connection, reset_queries | |
| from django.test.utils import override_settings | |
| import time | |
| # Log all queries | |
| @override_settings(DEBUG=True) | |
| def analyze_queries(func): | |
| def wrapper(*args, **kwargs): | |
| reset_queries() | |
| start = time.time() | |
| result = func(*args, **kwargs) | |
| end = time.time() | |
| print(f"Function: {func.__name__}") | |
| print(f"Number of queries: {len(connection.queries)}") | |
| print(f"Time taken: {end - start:.2f}s") | |
| for query in connection.queries: | |
| print(f"SQL: {query['sql']}") | |
| print(f"Time: {query['time']}s\n") | |
| return result | |
| return wrapper | |
| # Usage | |
| @analyze_queries | |
| def get_user_posts(user_id): | |
| user = User.objects.get(id=user_id) | |
| posts = user.posts.all() | |
| return list(posts) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment