2

What is the fastest way to truncate a table in the Django ORM based on the database type in a view? I know you can do this for example

Books.objects.all().delete()

but with tables containing millions of rows it is very slow. I know it is also possible to use the cursor and some custom SQL

from django.db import connection
cursor = connection.cursor()
cursor.execute("TRUNCATE TABLE `books`")

However, the TRUNCATE command does not work with SQLite. And if the database moves to another db type, I need to account for that.

Any ideas? Would it be easier to just drop the table and recreate in my view?

4

1 回答 1

3

Django's .delete() method is indeed very slow, as it loads the IDs of each object being deleted so that a post_save signal can be emitted.

This means that a simple connection.execute("DELTE FROM foo") will be significantly faster than Foo.objects.delete().

If that's still too slow, a truncate or drop+recreate is definitely the way to go. You can get the SQL used to create a table with: output, references = connection.creation.sql_create_model(model, style), where style = django.core.management.color_style() (this is taken from https://github.com/django/django/blob/master/django/core/management/sql.py#L14).

于 2013-03-30T20:49:08.797 回答