如何查看Django ORM執(zhí)行的SQL語(yǔ)句的實(shí)現(xiàn)
Django ORM對(duì)數(shù)據(jù)庫(kù)操作的封裝相當(dāng)完善,日常大部分?jǐn)?shù)據(jù)庫(kù)操作都可以通過(guò)ORM實(shí)現(xiàn)。但django將查詢過(guò)程隱藏在了后臺(tái),這在開(kāi)發(fā)時(shí)可能會(huì)略顯晦澀,并且使用方式不當(dāng)還會(huì)造成開(kāi)銷過(guò)大。
那么如何查看django何時(shí)執(zhí)行了什么sql語(yǔ)句呢?答案是使用Logging。
先直接上方法,在settings.py中加入LOGGING選項(xiàng),調(diào)整logging等級(jí)為DEBUG即可:
LOGGING = { ’version’: 1, ’disable_existing_loggers’: False, ’formatters’: { ’simple’: { ’format’: ’[%(asctime)s] %(message)s’ }, }, ’handlers’: { ’console’: { ’level’: ’DEBUG’, ’class’: ’logging.StreamHandler’, ’formatter’: ’simple’ }, }, ’loggers’: { ’django’: { ’handlers’: [’console’], ’level’: ’DEBUG’, }, },}
然后啟動(dòng)runserver,瀏覽需要訪問(wèn)數(shù)據(jù)庫(kù)的頁(yè)面,在shell中即可看見(jiàn)相關(guān)日志,如下:
[2018-04-21 21:09:14,676] (0.002) SELECT `blog_article`.`id`, `blog_article`.`title`, `blog_article`.`cover`, `blog_article`.`content`, `blog_article`.`pub_date`, `blog_article`.`category_id`, `blog_article`.`views`, `blog_category`.`id`, `blog_category`.`name` FROM `blog_article` INNER JOIN `blog_category` ON (`blog_article`.`category_id` = `blog_category`.`id`) WHERE `blog_article`.`pub_date` < ’2018-04-21 13:09:14.601856’ ORDER BY `blog_article`.`pub_date` DESC LIMIT 10; args=(’2018-04-21 13:09:14.601856’,)[2018-04-21 21:09:14,678] (0.000) SELECT (`blog_article_topics`.`article_id`) AS `_prefetch_related_val_article_id`, `blog_topic`.`id`, `blog_topic`.`name`, `blog_topic`.`number` FROM `blog_topic` INNER JOIN `blog_article_topics` ON (`blog_topic`.`id` = `blog_article_topics`.`topic_id`) WHERE `blog_article_topics`.`article_id` IN (3, 4, 5, 6, 7, 8, 9, 10, 11, 12) ORDER BY `blog_topic`.`number` ASC; args=(3, 4, 5, 6, 7, 8, 9, 10, 11, 12)[2018-04-21 21:09:14,708] 'GET / HTTP/1.1' 200 22325
上面打印出的日志是我的博客首頁(yè)獲取前十篇文章時(shí)所執(zhí)行的部分SQL語(yǔ)句,其對(duì)應(yīng)的QuerySet為
Article.objects.filter(pub_date__lt=timezone.now())[:10] .defer(’author’, ’category__number’) .select_related(’category’) .prefetch_related(’topics’)
通過(guò)Logging不僅可以查看SQL語(yǔ)句,還可以由此知道django何時(shí)執(zhí)行了SQL。在某些情況下我們可以通過(guò)這種方式判斷,后臺(tái)是否重復(fù)執(zhí)行了SQL語(yǔ)句,便于指導(dǎo)數(shù)據(jù)庫(kù)訪問(wèn)優(yōu)化。
Django使用Python的內(nèi)建的logging模塊執(zhí)行系統(tǒng)日志記錄。
到此這篇關(guān)于如何查看Django ORM執(zhí)行的SQL語(yǔ)句的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Django ORM執(zhí)行SQL語(yǔ)句內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. python實(shí)現(xiàn)讀取類別頻數(shù)數(shù)據(jù)畫水平條形圖案例2. python中PyQuery庫(kù)用法分享3. python操作數(shù)據(jù)庫(kù)獲取結(jié)果之fetchone和fetchall的區(qū)別說(shuō)明4. php5.6不能擴(kuò)展redis.so的解決方法5. Ajax實(shí)現(xiàn)頁(yè)面無(wú)刷新留言效果6. CSS3實(shí)現(xiàn)動(dòng)態(tài)翻牌效果 仿百度貼吧3D翻牌一次動(dòng)畫特效7. ASP.NET MVC前臺(tái)動(dòng)態(tài)添加文本框并在后臺(tái)使用FormCollection接收值8. PHP獲取時(shí)間戳等相關(guān)函數(shù)匯總9. AJAX實(shí)現(xiàn)數(shù)據(jù)的增刪改查操作詳解【java后臺(tái)】10. php使用正則驗(yàn)證密碼字段的復(fù)雜強(qiáng)度原理詳細(xì)講解 原創(chuàng)
