1

Using MyModel.objects.all().delete() may take a lot of time. Is there any way to speed up the process?

Assumptions:

  • I want to delete all instances of MyModel
  • I also want to delete any models that have a ForeignKey to MyModel
  • I know a priori which models they are
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Jonathan Livni
  • 101,334
  • 104
  • 266
  • 359

1 Answers1

3

Use raw sql:

from django.db import connection
cursor = connection.cursor()
cursor.execute("set foreign_key_checks = 0")
cursor.execute("truncate table table_a")
cursor.execute("truncate table table_b")
# ...
cursor.execute("set foreign_key_checks = 1")

If you want to delete all models, you can even use the db to generate the sql statements:

from django.db import connection
cursor = connection.cursor()
cursor.execute("set foreign_key_checks = 0")
cursor.execute("select concat('truncate table ',table_schema,'.',table_name,';') as sql_stmt from information_schema.tables where table_schema = 'your_schema_name' and table_type = 'base table'")
for sql in [sql[0] for sql in cursor.fetchall()]:
    cursor.execute(sql)
cursor.execute("set foreign_key_checks = 1")

(the sql tricks are taken from here)

Community
  • 1
  • 1
Jonathan Livni
  • 101,334
  • 104
  • 266
  • 359
  • I think that "set foreign_key_checks = 0" thing is for MySQL only, right? On Oracle, you would have to explicitly disable each foreign key that points to a table before truncating it. I found that in Oracle, I could keep 90% of the speed benefit by truncating my "child" table (many rows), then using a normal delete on my "parent" table (few rows). – Nick Perkins Jan 31 '13 at 19:47