2011-01-14 70 views
0

使用MyModel.objects.all().delete()可能需要很多的时间。有什么办法可以加快这个过程吗?如何加快django的delete()?

假设:

  • 我要删除我也想删除有一个ForeignKey来为MyModel
  • 我知道先验他们是哪个型号的任何模型为MyModel
  • 所有实例

回答

3

使用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") 

如果要删除所有车型,您甚至可以使用数据库生成SQL语句:

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

(在SQL技巧是从here拍摄)

+0

我认为“设置FOREIGN_KEY_CHECKS = 0”事情只针对MySQL,对吧?在Oracle上,您必须在截断前禁用指向表的每个外键。我发现在Oracle中,通过截断我的“子”表(多行),然后在我的“父”表(少数行)上使用正常删除,我可以保持90%的速度优势。 – 2013-01-31 19:47:59