13
votes

How do you view the SQL generated by Django for a DELETE?

When doing a SELECT operation on a query set, you can do this:

>>> qs = Entry.objects.filter(date__gt='2010-06-01')
>>> qs.query.as_sql()
('SELECT ...)

But I don't know how to get the SQL for what happens when I do qs.delete().

It looks a bit more involved because Django "emulates the behavior of the SQL constraint ON DELETE CASCADE" when deleting objects.

(Background: trying to debug an IntegrityError generated by a foreign key constraint when deleting a subclassed model object.)

2
You can check DB error log :) - Dmitry Shevchenko
Did you solve the IntegrityError? I'm having the same problem here. Weird fact: myobject.delete() works from "manage shell" but fails from the view ??? - Sdra

2 Answers

16
votes

This works well enough:

>>> from django.db import connection
>>> connection.queries[:-10]

Thought the exceptions occurred before the queries were added to connection.queries, but they are indeed present.

2
votes

You could try running django-debug-toolbar and see the queries that way.