How to TRUNCATE TABLE using Django's ORM? How to TRUNCATE TABLE using Django's ORM? django django

How to TRUNCATE TABLE using Django's ORM?


The closest you'll get with the ORM is Book.objects.all().delete().

There are differences though: truncate will likely be faster, but the ORM will also chase down foreign key references and delete objects in other tables.


You can do this in a fast and lightweight way, but not using Django's ORM. You may execute raw SQL with a Django connection cursor:

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


You can use the model's _meta property to fill in the database table name:

from django.db import connectioncursor = connection.cursor()cursor.execute('TRUNCATE TABLE "{0}"'.format(MyModel._meta.db_table))

Important: This does not work for inherited models as they span multiple tables!