from django.http import HttpResponseRedirect
from django.core.exceptions import MiddlewareNotUsed

class SqlDebuggingRedirWrapMiddleware(object):
    def __init__(self):
        if not (getattr(settings, 'DEBUG', False)):
            raise django.exceptions.MiddlewareNotUsed()
        
    def process_response(self, request, response):
        if isinstance(response, HttpResponseRedirect):
            request.session['_redir_queries'] = connection.queries
        return response
    
    def process_request(self, request):        
        if '_redir_queries' in request.session:
            connection.queries[0:0] = request.session['_redir_queries']
            del request.session['_redir_queries']