From c32a7651a277d54b5e46c87264810c1d15428a9f Mon Sep 17 00:00:00 2001 From: Josiah White Date: Thu, 20 Oct 2022 11:42:10 -0700 Subject: [PATCH] Fixed #27587 -- Adding examples of QuerySet.query.__str__() to docs. --- docs/intro/tutorial02.txt | 8 +++++++- docs/topics/db/queries.txt | 13 +++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/docs/intro/tutorial02.txt b/docs/intro/tutorial02.txt index ee0707456d..99812673d4 100644 --- a/docs/intro/tutorial02.txt +++ b/docs/intro/tutorial02.txt @@ -473,8 +473,14 @@ Save these changes and start a new Python interactive shell by running >>> from polls.models import Choice, Question # Make sure our __str__() addition worked. - >>> Question.objects.all() + >>> q = Question.objects.all() + >>> q ]> + # Print the SQL used to query the database + >>> from pprint import pprint + >>> pprint(str(q.query)) + ('SELECT "polls_question"."id", "polls_question"."question_text", ' + '"polls_question"."pub_date" FROM "polls_question"') # Django provides a rich database lookup API that's entirely driven by # keyword arguments. diff --git a/docs/topics/db/queries.txt b/docs/topics/db/queries.txt index 5114efb57d..da9b9f9596 100644 --- a/docs/topics/db/queries.txt +++ b/docs/topics/db/queries.txt @@ -336,6 +336,19 @@ objects from the database. However, that's far from all there is; see the :ref:`QuerySet API Reference ` for a complete list of all the various :class:`~django.db.models.query.QuerySet` methods. + +Printing the ``QuerySet`` SQL +-------------------------- + +When debugging a query, it may be useful to see the SQL generated by a +queryset. You may do this by converting the ``query`` attribute to a string. + + >>> q = Entry.objects.all() + >>> str(q.query) + +This prints the SQL that is used to query the database. From there, you may +looks for unexpected clauses, etc. + .. _limiting-querysets: Limiting ``QuerySet``\s