Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

View the SQL queries for Django queryset delete

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.)

like image 516
tcarobruce Avatar asked Dec 29 '10 19:12

tcarobruce


1 Answers

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.

Here's another method which relies on Django internals and doesn't include queries to do cascading deletes, but doesn't require executing the query:

from django.db.models import sql

qs = Entry.objects.filter(date__gt='2010-06-01')
query = qs.query.clone()
query.__class__ = sql.DeleteQuery
print(query)
like image 126
tcarobruce Avatar answered Oct 15 '22 04:10

tcarobruce