When working with databases, we often have to reset a database because we fill it with useless data. Sometimes, we even end up setting up a database based on an error-prone database schema. Sometimes, we even end up changing the business logic, which adjusts the whole database design. These situations are pretty common in the field of Computer Science, and some good tools and commands have been constructed to handle them.
In Django, if we end up in any such situation, we have to reset the migrations and the database. When resetting migrations, we have a few options on the list.
- Reset the Whole Database
- Revert a Django App back to some old migrations
Reset the Whole Database in Django
When we have to reset the whole database in Django, there are a few options on the list.
- If we are using Django’s default SQLite database, we can delete the database file
db.sqlite3and then delete all the
migrationsfolders inside all the apps. After deleting the
migrationsfolders, we can remake the migrations and migrate them using two commands; namely,
python manage.py makemigrationsand
python manage.py migrate.
- If we are using some other relational database such as PostgreSQL or MySQL, we can either delete all the tables using a database management tool such as
DBeaver, etc. or manually using the command line. Or, we can create a whole new database and then connect it to our Django Project. Note that, for both cases, one should first delete all the
migrationsfolders and then remake the migrations and, lastly, migrate them.
- Another option is to use Django’s
manage.pycommand to clear the whole database for us. The command is
python manage.py flush. Again, after using this command, we have to delete all the
migrationsfolders and then make the new migrations.
Revert a Django App back to its old migrations
If we don’t have to reset the whole database but roll back the migrations for a specific Django App, we have two options for that. First, we can reverse a Django App’s current migrations to some old migrations. Second, we can reset all the migrations for the Django App.
If we have to migrate back from some latest migration, let’s say 0014, to an older migration, let’s say 0008, we can use the following commands.
python manage.py migrate AppName 0008 --- OR --- python manage.py migrate AppName 0008_migration_name
And, if we have to reset all the migrations for a Django App, we can use the following command.
python manage.py migrate AppName zero
Note that sometimes migrations can be irreversible. Generally, this condition arises when some significant changes have been made to the Django Models. When we try to revert back to such a migration, Django will raise an