Django how to see generated SQL query?

后端 未结 2 998
再見小時候
再見小時候 2021-02-10 13:10

I have a form which takes data and is supposed to insert it into a database. When I am processing that form it gives me a value error, but when I go to the database and try to i

2条回答
  •  眼角桃花
    2021-02-10 14:06

    How about using logging?

    you can add this in settings.py

    LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'handlers': {
            'console': {
                'level': 'DEBUG',
                'class': 'logging.StreamHandler',
            },
        },
        'loggers': {
            'django': {
                'handlers': ['console'],
                'level': 'DEBUG',
                'propagate': True,
            },
        },
    }
    

    and you can add this in your any views.py

    import logging
    
    l = logging.getLogger('django.db.backends')
    l.setLevel(logging.DEBUG)
    l.addHandler(logging.StreamHandler())
    

    In your console, you can check SQL query.

    Another way

    go shell

    python manage.py shell
    
    >>from yourmodel import Example
    >>queryset = Example.objects.all()
    >>print(queryset.query)
    

    you can see raw query string.

提交回复
热议问题