代码之家  ›  专栏  ›  技术社区  ›  gath

Django如何在管理shell中查看查询

  •  6
  • gath  · 技术社区  · 14 年前

    如何从管理shell界面查看我的django查询

    我尝试过使用它,但给出了通过django服务器传递的查询

    from django.db import connection
    connection.queries()
    

    我在某个地方见过,不记得在哪里??

    4 回复  |  直到 8 年前
        1
  •  8
  •   Community Lee    7 年前

    query

    qs = MyModel.objects.all()
    print qs.query
    

    update()

    from django.db import connection
    MyModel.objects.all().update(foo = 'bar')
    print connection.queries 
    # print connection.queries[-1] # if you want to see only the last query
    

    django-debug-toolbar snippet @rubayeet

        2
  •  3
  •   Chillar Anand    8 年前

    django extensions

    $ pip install django-extensions
    

    ./manage.py shell_plus --print-sql
    

    In [1]: Book.objects.all()
    Out[1]: SELECT "book_book"."id", "book_book"."name", "book_book"."author_id" FROM "book_book" LIMIT 21
    
    Execution time: 0.087548s [Database: default]
    
    <QuerySet [<Book: The Stranger>, <Book: Atlas Shrugged>]>
    

    --print-sql

    SHELL_PLUS_PRINT_SQL = True
    

    LOGGING = {
        'version': 1,
        'loggers': {
            'django.db.backends': {
                'level': 'DEBUG',
                'handlers': ['console'],
            }
        },
        'handlers': {
            'console': {
                'level': 'DEBUG',
                'class': 'logging.StreamHandler',
                'filters': ['require_debug_true'],
            }
        },
        'filters': {
            'require_debug_true': {
                '()': 'django.utils.log.RequireDebugTrue',
            }
        },
    }
    

        3
  •  1
  •   Sam Dolan    14 年前

    your_query = YourModel.objects.all()
    print your_query.query
    

        4
  •  0
  •   rubayeet    14 年前