DEV Community

codewitgabi
codewitgabi

Posted on

Database migrations inconsistency in django

Working with django can be really cool until you bumb into migrations inconsistency.

Migrations inconsistency happens when there is a rapid change in your models. Say, field altering, or change of table name. A quick fix is to probably delete the migration files, re-makemigrations and then migrate which may or may not work. Another try is to delete the database which would be tempting to do but then what if you are working on a production database. Of course, that's not a very nice approach to take.

This leads us to database backup. So, you have thought of everything but it seems deleting the database might be the best approach? No problem, all you need to do is backup the database and then as soon as a new one is created, you quickly inject the data back into the database.

Database backup with django

Django is a robust framework with batteries (lots of it), making it easier to perform database operations with its Object-Relational Mapper. Database backup is not an exemption. To backup your database, run the following commands.

python3 manage.py dumpdata > db-backup.json
Enter fullscreen mode Exit fullscreen mode

Where db-backup.json is the name of the file that will contain your database data.

Reloading the database

To load the data back into the database, run the command below

python3 manage.py loaddata db-backup.json
Enter fullscreen mode Exit fullscreen mode

And voila, you now have your "untampered" database

Just a brief info. Interships are a nice way to get your hands "dirty". hng is one place to get started for free and also hng-premium for a rich-full internship with lots of opportunities.

Top comments (0)