Custom Search

Monday, March 9, 2015

How to Get the SQL Query from Django QuerySet

1)
Open django shell
#python manage.py shell

2)
Import the model class
>>> from bla.models import Building

3)
Print the SQL query
>>> print Building.objects.all().query
OR
>>> Building.objects.all().query.__str__()




2 comments:

  1. How do you add a where command in Django like select this from this wherer a = b or something like that

    ReplyDelete
  2. >>>print(Rule.objects.filter(rule_name="rule").query.__str__())
    SELECT `de1_rule`.`rule_id`, `de1_rule`.`rule_threshold_id_id`, `de1_rule`.`rule_name`, `de1_rule`.`rule_type`, `de1_rule`.`description`, `de1_rule`.`rule_category`, `de1_rule`.`created_by`, `de1_rule`.`created_date`, `de1_rule`.`updated_by`, `de1_rule`.`updated_date` FROM `de1_rule` WHERE `de1_rule`.`rule_name` = rule

    ReplyDelete