Login

print SQL statements

Author:
zuzelvp
Posted:
February 9, 2010
Language:
Python
Version:
1.1
Score:
0 (after 0 ratings)

Modifies the as_sql methods to print the queries.

 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. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 8 months ago

Comments

Please login first before commenting.