Django: show/log ORM sql calls from python shell

后端 未结 7 1113
臣服心动
臣服心动 2020-11-30 16:33

Using the excellent Django-Devserver I\'m finding all kinds of interesting and unexpected SQL calls in my code. I wanted to find where the calls are coming from, and so I\'m

相关标签:
7条回答
  • 2020-11-30 17:14

    Use django extensions.

    pip install django-extensions
    ./manage.py shell_plus --print-sql
    

    For production environments it might not work due to debug settings.

    0 讨论(0)
  • 2020-11-30 17:19

    If you're in the shell, or anywhere for that matter, you can use the queryset method

    query.as_sql()
    

    to print the SQL command.

    ie:

    MyModel.objects.all().query.as_sql()
    
    0 讨论(0)
  • 2020-11-30 17:21

    I was trying to use "Django: show/log ORM sql calls from python shell" in a shell on a production server, and it wasn't working. Eventually someone pointed out that it will only do this debug logging when DEBUG = True. But you can work around that like this:

    import logging
    from django.db import connection
    connection.force_debug_cursor = True  # Change to use_debug_cursor in django < 1.8
    l = logging.getLogger('django.db.backends')
    l.setLevel(logging.DEBUG)
    l.addHandler(logging.StreamHandler())
    

    I'm leaving this here so I can find it later, and hopefully it saves someone else the same digging I did.

    0 讨论(0)
  • 2020-11-30 17:21

    If you're really serious about wanting to see/log all SQL queries, you'll want to try Django 1.3 (currently in alpha, but soon to be production) which enables Python loggers for many components, including the database backends.

    Of course, if you're stuck using a stable version of Django, you can get the same effect relatively easily by patching django/db/models/sql/compiler.py by adding this to the bottom of the import list:

    import logging
    _querylogger = logging.getLogger( 'sql.compiler' )
    

    The find the SQLCompiler::execute_sql() method and change:

        cursor = self.connection.cursor()
        cursor.execute( sql, params )
    

    to this:

        cursor = self.connection.cursor()
        _querylogger.info( "%s <= %s", sql, params )
        cursor.execute( sql, params )
    
    0 讨论(0)
  • 2020-11-30 17:35
    qs = YourModel.objects.all()
    
    qs.query.get_compiler('default').as_sql()
    
    0 讨论(0)
  • 2020-11-30 17:38

    If you're using Django 1.3:

    import logging
    l = logging.getLogger('django.db.backends')
    l.setLevel(logging.DEBUG)
    l.addHandler(logging.StreamHandler())
    
    0 讨论(0)
提交回复
热议问题