From d91095def47a9916300b6f1ce970befcd497381f Mon Sep 17 00:00:00 2001 From: Simon Charette Date: Sun, 24 May 2020 09:18:12 -0400 Subject: [PATCH] [3.1.x] Fixed #31624 -- Avoided subquery usage on QuerySet.all().delete(). Thanks Adam Johnson for the report. Regression in 7acef095d73322f45dcceb99afa1a4e50b520479. Backport of 972000420e08703dd4981466ff67adcd5a61ad4b from master --- django/db/models/sql/compiler.py | 2 ++ tests/delete/tests.py | 6 ++++++ 2 files changed, 8 insertions(+) diff --git a/django/db/models/sql/compiler.py b/django/db/models/sql/compiler.py index c368a59226..2c51561ae8 100644 --- a/django/db/models/sql/compiler.py +++ b/django/db/models/sql/compiler.py @@ -1400,6 +1400,8 @@ class SQLInsertCompiler(SQLCompiler): class SQLDeleteCompiler(SQLCompiler): @cached_property def single_alias(self): + # Ensure base table is in aliases. + self.query.get_initial_alias() return sum(self.query.alias_refcount[t] > 0 for t in self.query.alias_map) == 1 def _as_sql(self, query): diff --git a/tests/delete/tests.py b/tests/delete/tests.py index c32ebba83f..e1ec26bc1a 100644 --- a/tests/delete/tests.py +++ b/tests/delete/tests.py @@ -605,6 +605,12 @@ class DeletionTests(TestCase): class FastDeleteTests(TestCase): + def test_fast_delete_all(self): + with self.assertNumQueries(1) as ctx: + User.objects.all().delete() + sql = ctx.captured_queries[0]['sql'] + # No subqueries is used when performing a full delete. + self.assertNotIn('SELECT', sql) def test_fast_delete_fk(self): u = User.objects.create(