How to Delete and Reset a PostgreSQL Database in Django

In this tutorial, you will learn how to completely delete all tables from your PostgreSQL database and start fresh in a Django project. This process is useful for testing or when you need to clean your database.

Commands to delete the entire database

1. Connect to your database

Use the following command to connect to your database from the terminal:

psql -h <host> -p <port> -U <username> -d <dbname>

Replace the values with those of your PostgreSQL instance.

2. Drop the entire schema and recreate an empty one

Inside psql, run these commands to drop everything in the public schema:

DROP SCHEMA public CASCADE;
CREATE SCHEMA public;

These commands will delete all tables, views, and dependencies in the public schema and recreate it empty.

3. Verify that the schema is clean

Confirm that there are no tables by running:

\dt

The result should be: No relations found.

Steps to reset the database in Django

1. Apply migrations

Run this command for Django to recreate the tables:

python3 manage.py migrate

2. Create a superuser

After applying migrations, create a superuser to access Django admin:

python3 manage.py createsuperuser

3. Load test data (optional)

If you have fixtures with test data, you can load them by running:

python3 manage.py loaddata <fixture_name>.json

Command summary

To delete and reset your PostgreSQL database:

-- Delete all contents from the public schema
DROP SCHEMA public CASCADE;

-- Recreate the empty public schema
CREATE SCHEMA public;

-- Confirm the schema is clean
\dt

Additional notes

  • Backup: Before making these changes, make sure you have a backup of your database.
  • Correct environment: Verify that you are connected to the correct database before running the commands.

I hope this tutorial is helpful! If you have questions or comments, feel free to share them.