tags:

views:

184

answers:

2

Hello!

To empty database table, I use this SQL Query:

TRUNCATE TABLE `books`

How to I Truncate table using Django models and orm?

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

Book.objects.truncate()
+3  A: 

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.

Ned Batchelder
Thank you. This does the trick. Speed is not important at my case.
Silver Light
+3  A: 

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

from django.db import connection
cursor = connection.cursor()
cursor.execute("TRUNCATE TABLE `books`")
Shamanu4
Thank you, but I prefer to make my apps to work with as much database engines as possible and not to use raw sql's
Silver Light
TRUNCATE TABLE is a part of the "typical" SQL syntax, although only officially only part of SQL:2008. Django supports Postgres, MySQL, SQLite*, and Oracle. http://www.postgresql.org/docs/8.1/interactive/sql-truncate.htmlhttp://dev.mysql.com/doc/refman/4.1/en/truncate-table.htmlhttp://download.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_10006.htm*SQLite is missing TRUNCATE [TABLE] support, you need to use DELETE FROM for it. This of course, is really only applicable if you need performance.
Aea