How to get equivalent SQL statement corresponding to django orm

created at 07-16-2021 views: 1

Sometimes you want to know how Django ORM makes our queries execute, or what the SQL corresponds to the code you write. This is very straightforward. The content of sql can be obtained through str(queryset.query).

Suppose you have a model: Event. In order to get all records, you will write something like Event.objects.all(), and then execute str(queryset.query).

example

>>> queryset = Event.objects.all()
>>> print(queryset.query)
SELECT "events_event"."id", "events_event"."epic_id",
    "events_event"."details", "events_event"."years_ago"
    FROM "events_event"

another example

>>> queryset = Event.objects.filter(years_ago__gt=5)
>>> print(queryset.query)
SELECT "events_event"."id", "events_event"."epic_id", "events_event"."details",
"events_event"."years_ago" FROM "events_event"
WHERE "events_event"."years_ago" > 5

If your DEBUG = True, all queries are logged, and you can get them by visiting connection.queries:

from django.db import connections

connections['default'].queries
Please log in to leave a comment.