Reinitializing a Django app

Abenezer Belachew

Abenezer Belachew ยท June 14, 2024

3 min read

  • I enjoy tackling migrations related issues, whether it involves working with newly generated Django migration files or directly at the database level. However, some days I just don't have the patience for it. On those days, it's easier to wipe everything and start fresh, especially for projects that have gazillions of migration files and obscure error messages. It's often simpler to delete all migrations and related tables in the database and run a migration as if it were new.

  • Here's a quick list of steps to take to achieve that:

    • I'll use an example app called samples and my examples are in PostgreSQL, but the process should be easy to replicate in any of the databases that work well with Django.

1. Delete Migration Files in the app

  • Delete the migrations director of the app you want to yank.
  • Alternatively, if you're not using a version control system or don't have a backup, you can rename it to something other than "migrations" in case things go wrong.

2. Drop Associated Databse tables

  • Manually drop the tables associatd with the app using SQL commands.

2.1 List tables

  • List all the tables associated with your app. By default, Django prefixes the names of the tables associated with an app with the app's name, so they should be easy to find.

    • For example, if you have a model called Car in your samples app, the generate table will be named samples_car in the database.
  • If you've explicitly defined the name of your table, using db_table or whatever obscure way you've come up with, use the name you defined.

  • In this case, since the app is named samples, Django is expected to create tables for the models inside the samples app with samples_ preceding the model name.

  • To fetch all the tables that start with samples_, you could use something like this:

SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'public'
AND table_name LIKE 'samples_%';
  • This will return the tables that start with samples_.
       table_name       
------------------------
 samples_car
 samples_router
 samples_book
(3 rows)

2.2 Drop Tables

  • For each table, generate a DROP TABLE command.
DROP TABLE "samples_car";
DROP TABLE "samples_router";
DROP TABLE "samples_book";
  • You may need to add CASCADE to some of them depending on their relation to other models (tables).

3. Remove app from django_migrations table

  • The django_migrations table is used by Django to keep track of the migrations that have been applied. It's how it decides which migrations need to be run.
  • To remove all the records for the samples app, run:
DELETE FROM django_migrations WHERE app = 'samples';

4. Run makemigrations and then migrate

  • Finally, create new migrations and apply them:
python manage.py makemigrations
python manage.py migrate
๐Ÿ’๏ธ