python

Django: How to Delete All Rows from a Table

If you need to delete all the rows from a table in Django, there are a few different ways you can do it. In this article, we'll show you how to delete all rows from a table in Django using the Django ORM, as well as how to delete all rows from a table using raw SQL.

Delete all records from a table using Django

Assuming you would like an introduction to deleting all records from a table using the Django web framework:

Django is a powerful web framework that makes it easy to build web applications. One of its key features is its object-relational mapper (ORM), which lets you interact with databases in a more abstract way.

Code example

def delete_all_rows(self):
    User.objects.all().delete()

The ORM is great for doing simple CRUD operations (create, read, update, delete), but sometimes you need to delete all records from a table. To do this, you can use the django.db.models.objects.all().delete() method.

This method takes an optional boolean parameter called a cascade. If cascade is True, all related objects will also be deleted. For example, if you have a table of blog posts and each post has comments, setting cascade to True will delete all of the comments for each post.

Be careful when using this method, as it will permanently delete data from your database.

Basic syntax

Modal_Name.objects.all().delete()

This code deletes all of the rows in the User table. We have created a function delete_all_rows() in Django and inside that function we execute the query User.objects.all().delete() that will delete all the records from the table created with Django model - User.

Remove all data from all tables using the flush command

The flush command in Django will remove all data from all tables in your database. This is a destructive operation and should be used with caution.

Command

python manage.py flush

The above command will remove all the data from each table in the Database. But the table will exist in the Database.

Remove all data from a single table using shell commands

The below commands will remove all data from a single table using shell commands in Django. This can be useful if you need to start from scratch with a new table or if you want to remove all data from an existing table.

python manage.py shell
>> from app.models import Student
>> Student.objects.all().delete()

The above commands would delete all of the Student objects from the database.

Was this helpful?