使用MyModel.objects.all()。delete()可能需要 很多 。有没有办法加快这个过程?
假设:
答案 0 :(得分: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")
如果要删除所有模型,甚至可以使用db生成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)