How to Delete All Objects of a Database Table in Django


In this article, we show how to delete all objects of a database table in Django.

Of course, you can get into the admin of your site and delete all rows manually, but this would be tedious, especially if the database table has a lot of objects (rows of data). Therefore, it's best to do this in code.

Let's say we have a database table called Car.

To delete all objects from this Car database, the following line of code would do this.

This represents the file (in which we delete the objects of the Car database table).

So, we have our typical file.

We import the Car database table from the file.

We then have our functon-based view, which we call showthis() in this case.

In the first line of the function-based view, we delete all objects of the Car database table using the line, Car.objects.all().delete()

Besides being done in the file, this can also be done in the Python shell by writing the line, py shell, in the command prompt of your computer.

And this is all that is required to delete all objects from a database table in Django.

Related Resources

How to Randomly Select From or Shuffle a List in Python

HTML Comment Box is loading comments...