How to TRUNCATE TABLE using Django's ORM?


Question

To empty a database table, I use this SQL Query:

TRUNCATE TABLE `books`

How to I truncate a table using Django's models and ORM?

I've tried this, but it doesn't work:

Book.objects.truncate()
1
45
8/10/2016 9:58:32 PM

Accepted Answer

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.

59
6/7/2010 11:34:04 AM

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 connection
cursor = connection.cursor()
cursor.execute("TRUNCATE TABLE `books`")

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon