3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Djangoで実行されるSQLを確認する(SELECT編)

Posted at

はじめに

前にINSERTのSQLを表示してみましたが今回はより使い道がありそうなSELECT文を表示してみます。

SELECT文を表示する方法

わかってしまうと非常に簡単でした。

sql_dumper.py
def show_select_sql(queryset):
    compiler = queryset.query.get_compiler(using=queryset.db)
    return compiler.as_sql()

これを導くまでの話はこっちの読解記事を参照してください。

生成されるSQLの確認

Djangoチュートリアル その2に載っている検索がどういうSQLになるのか試してみましょう。

all

>>> from sql_dumper import show_select_sql
>>> from polls.models import Question
>>> show_select_sql(Question.objects.all())
('SELECT "polls_question"."id", "polls_question"."question_text", "polls_question"."pub_date" FROM "polls_question"', ())

id指定

>>> show_select_sql(Question.objects.filter(id=1))
('SELECT "polls_question"."id", "polls_question"."question_text", "polls_question"."pub_date" FROM "polls_question" WHERE "polls_question"."id" = %s', (1,))

CharFieldの開始文字列指定

>>> show_select_sql(Question.objects.filter(question_text__startswith='What'))
('SELECT "polls_question"."id", "polls_question"."question_text", "polls_question"."pub_date" FROM "polls_question" WHERE "polls_question"."question_text" LIKE %s ESCAPE \'\\\'', ('What%',))

DateTimeFieldの年指定

>>> from django.utils import timezone
>>> current_year = timezone.now().year
>>> show_select_sql(Question.objects.filter(pub_date__year=current_year))
('SELECT "polls_question"."id", "polls_question"."question_text", "polls_question"."pub_date" FROM "polls_question" WHERE "polls_question"."pub_date" BETWEEN %s AND %s', ('2016-12-31 15:00:00', '2017-12-31 14:59:59.999999'))

問題なく出てますね。WHEREの部分についてはまだコード読んでないのでどう頑張ってこのようなSQLを構築しているのかを見るのもおもそしろそうです。

3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?