Using the ORM - print the actual SQL

There will come a time in any Django developer's career when you will actually need to look at the SQL that is going on under the hood. For myself that is typically to understand the difference between 2 queries when doing a refactor.

There are a few ways to do this, and this depends on the context where the query exists, but for me the easiest way is to print the query attribute of any QuerySet as shown below.


>>> low_stock = Product.objects.filter(quantity__lt=5)
>>> print(low_stock.query)
SELECT "temp_product"."id", "temp_product"."name", "temp_product"."description", "temp_product"."quantity" FROM "temp_product" WHERE "temp_product"."quantity" < 5

An aside is that we are using manage.py shell here to access Django in a python interpreter and really should be the preferred way of doing adhoc queries and work against your project. It WILL level up your Django knowledge and it will be available in every environment that your project exists!