print SQL statements

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from optparse import make_option
import os
import types

from django.core.management.commands.runserver import Command as BaseCommand
from django.db.models.sql import query
from django.db.models.sql import subqueries


class Command(BaseCommand):
    help = "Works as runserver but prints every SQL statement used."

    def handle(self, *args, **kwargs):
        log_query(query.Query)
        log_query(subqueries.DeleteQuery)
        log_query(subqueries.InsertQuery)
        log_query(subqueries.UpdateQuery)
        super(Command, self).handle(*args, **kwargs)


def log_query(cls):
    original_as_sql = cls.as_sql.im_func
    def new_as_sql(*args, **kwargs):
        q, args = original_as_sql(*args, **kwargs)
        print q.replace('"', '') % args
        print
        return q, args
    cls.as_sql = types.MethodType(new_as_sql, None, cls)

More like this

  1. Modify query string on a url by dnordberg 4 years, 11 months ago
  2. Continuous Integration command by berto 3 years, 7 months ago
  3. Extended Profiling Middleware by hauser 5 years, 3 months ago
  4. Interactive debugger and other Paste niceties by maxua 3 years, 8 months ago
  5. TerminalLoggingMiddleware by heckj 5 years, 11 months ago

Comments

(Forgotten your password?)