开发者

How to speed up django's delete()?

Using M开发者_StackOverflowyModel.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


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜