view query for prefetch_related

We all know we can use print(my_queryset.query) to examine a queryset’s “rendered” SQL.
Is there a way (other than checking the database logs, etc) to output the rendered SQL for the extra prefetch_related query(ies)?

See FAQ: Databases and models | Django documentation | Django

if DEBUG is True you can check the queries which have been run in django.db.connection.queries:

>>> import pprint
>>> from django.db import connection
>>> pizzas = list(Pizza.objects.prefetch_related('toppings'))
>>> 
>>> pprint.pp(connection.queries)
[{'sql': 'SELECT "pizza_pizza"."id", "pizza_pizza"."name" FROM "pizza_pizza"',
  'time': '0.001'},
 {'sql': 'SELECT ("pizza_pizza_toppings"."pizza_id") AS '
         '"_prefetch_related_val_pizza_id", "pizza_topping"."id", '
         '"pizza_topping"."name" FROM "pizza_topping" INNER JOIN '
         '"pizza_pizza_toppings" ON ("pizza_topping"."id" = '
         '"pizza_pizza_toppings"."topping_id") WHERE '
         '"pizza_pizza_toppings"."pizza_id" IN (5, 6, 4, 7)',
  'time': '0.001'}]

Otherwise, using the django-debug-toolbar, or django-extensions’s --print-sql option might suit your needs.

2 Likes

great, thanks :slight_smile: ===

Note: If you want all of the queries that have been issued, you can use the django.db.backends logger object to write all executed queries to your log. You can do this regardless of the debug setting. (There is a limit to the number of queries stored in the connection object.)