Django: 查看模型执行的SQL语句的方法及logging配置Django: 查看模型执行的SQL语句的方法及logging配置Django: 查看模型执行的SQL语句的方法及logging配置Django: 查看模型执行的SQL语句的方法及logging配置
  • 首页
  • 博客
  • 文件
  • 书签
  • 分析
  • 登录
Search
Generic filters

Django: 查看模型执行的SQL语句的方法及logging配置

Published by admin at 2022年8月22日
Categories
  • Django
Tags

前提:

app名称为core,models.py内容如下:

# coding:utf-8
from django.db import models

# Create your models here.   
class Province(models.Model):
    name = models.CharField(u'省份名称',max_length=32)
    code = models.IntegerField(verbose_name=u'区号', unique=True)
    
    def __str__(self):
        return self.name
    
    class Meta:
        verbose_name = u'省份列表'
        verbose_name_plural = u'省份列表'

法I:该方法只能查看select语句,对于其他更新保存的语句不能查看,会报错

例1.
res = User.objects.all()
print(res.query)
#SELECT 'user'.'id', 'user'.'name', 'user'.'age' FROM 'user'
例2.
>>> from core.models import Province
>>> print Province.objects.all().query
SELECT `core_province`.`id`, `core_province`.`name`, `core_province`.`code` FROM `core_province`

 

>>> from core.models import Province
>>> p = Province(name=u'广州', code='020')
>>> p.save().query
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'query'
>>> p.save()

也就是说只有 Queryset 有query方法。

法II:该方法会打印出所有执行过的sql语句

例1.
#1、先导入connection
from django.db import connection
#2、在python文件中打印
print(connection.queries)

封装成函数

def print_sql():
    # 1、先导入connection
    from django.db import connection
    # 2、在python文件中打印
    print(connection.queries)
例2.
>>> from core.models import Province
>>> from django.db import connection
>>> p = Province(name=u'河南', code='0371')
>>> p.save()
>>> print connection.queries
[{u'time': u'0.439', u'sql': u"INSERT INTO `core_province` (`name`, `code`) VALUES ('u5e7fu5dde', 20)"}, 
 {u'time': u'0.056', u'sql': u"UPDATE `core_province` SET `name` = 'u5e7fu5dde', `code` = 20 WHERE `core_province`.`id` = 3 "}, 
 {u'time': u'0.102', u'sql': u"INSERT INTO `core_province` (`name`, `code`) VALUES ('u6cb3u5357', 371)"}]

该方法会打印出所有执行过的sql语句,包括我在实验方法I时所执行的两个p.save()(第一个save()为INSERT,第二个save()为UPDATE)也都打印出来了。

例3.

Django.db.connection.queries – Here Django stores the history of all executed database queries in the order of their execution. Therefore,immediately after executing the request you can get it from here:

from django.db import connection
u = User.objects.filter(email__icontains='igor').first()
print(connection.queries[-1]["sql"])

It will then give you:

SELECT "users_user"."id", "users_user"."last_login", "users_user"."email" FROM "users_user" WHERE ("users_user"."is_registered" = true AND UPPER("users_user"."email"::text) LIKE UPPER('%igor%')) ORDER BY "users_user"."id" ASC LIMIT 1

As you can see, the 'real' SQL will be here, which you can copy and execute.

法III:Django查看原生SQL语句logging配置

Add the following to your Django settings file (settings.py):

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

This will log all SQL queries to console when DEBUG is True (during development).

Alternatively you can do each log separately this way:

import logging 
l = logging.getLogger('django.db.backends') 
l.setLevel(logging.DEBUG)
l.addHandler(logging.StreamHandler()) 
from blog.models import Entry 
Entry.objects.all()

发表回复 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注

Categories

  • 猫
  • Python
  • MySQL
  • Django
  • Html/CSS
  • JavaScript
  • Vue
  • RegExp
  • php
  • Practice
  • Virtualization
  • Linux
  • Windows
  • Android
  • NAS
  • Software
  • Hardware
  • Network
  • Router
  • Office
  • WordPress
  • SEO
  • English
  • Games
  • Recipes
  • living
  • Memorandum
  • Essays
  • 未分类

归档

©2015-2022 Alaica Blog support@alaica.com