debugger_queries decorator

Introduction

Today the #DjangoTip will be about using select_related and prefetch_related to improve our queries performance.

You can clone this project from http://github.com/LucasMagnum/django-tip-02 and follow the examples below.

It takes time to fully understand how select_related and prefetch_related works, so keep looking for other resources and I hope this post helps you to understand a bit more. Code and have fun ❤

debugger_queries decorator

import time
import functools

from django.db import connection, reset_queries


def debugger_queries(func):
    """Basic function to debug queries."""
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print("func: ", func.__name__)
        reset_queries()

        start = time.time()
        start_queries = len(connection.queries)

        result = func(*args, **kwargs)

        end = time.time()
        end_queries = len(connection.queries)

        print("queries:", end_queries - start_queries)
        print("took: %.2fs" % (end - start))
        return result

    return wrapper