November 15, 2014 · django python

How to show sql in console / shell in Django

SQL Queries can be debugged in Django manage.py shell, in the following ways:

 >>> a = Blog.objects.filter(entry__authors__name__isnull=True)
 >>> print a.query

 SELECT `docu_blog`.`id`, `docu_blog`.`name`, `docu_blog`.`tagline` FROM `docu_blog` 
 LEFT OUTER JOIN `docu_entry` ON ( `docu_blog`.`id` = `docu_entry`.`blog_id` ) 
 LEFT OUTER JOIN `docu_entry_authors` ON ( `docu_entry`.`id` = `docu_entry_authors`.`entry_id` ) 
 LEFT OUTER JOIN `docu_author` ON ( `docu_entry_authors`.`author_id` = `docu_author`.`id` ) 
 WHERE `docu_author`.`name` IS NULL
 >>> Blog.objects.filter(entry__authors__name__isnull=True).query.sql_with_params()

 >>> (u'SELECT `docu_blog`.`id`, `docu_blog`.`name`, `docu_blog`.`tagline` 
 FROM `docu_blog` 
 LEFT OUTER JOIN `docu_entry` ON ( `docu_blog`.`id` = `docu_entry`.`blog_id` )
 LEFT OUTER JOIN `docu_entry_authors` ON ( `docu_entry`.`id` = `docu_entry_authors`.`entry_id` )
 LEFT OUTER JOIN `docu_author` ON ( `docu_entry_authors`.`author_id` = `docu_author`.`id` )
 WHERE `docu_author`.`name` IS NULL', ())
  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket
Comments powered by Disqus