Loading Initial Data As A Migration Step in Django Project

There are some kinds of application that tightly rely on contents. Loading initial data is definitely required.

For you who already be familiar with python manage.py migrate, I’d like to introduce the way Django allows you to add any command to the migrate step.

When you run python manage.py makemigrations, you will get auto-generated migration files. There you can create your own migration file.

The picture below shows the migration file I created. It requires Migration class.
dependencies is not required. For this case we need it.

The operations is where the migration execute the action, RunPython is where Django allow us to add any extension for flexibility.

forwards_func is the function we code the action. and reverse_func is the one to run when you do migration reversion. Let’s discuss about reverse at the last section.
For this post, I’d to keep it simple. I don’t want to put loads of things here.

Let’s see how it looks like when you execute the python manage.py migrate with a fresh and clean database.
The picture below shows you that the migration called user.0044_load_init_data prints the “forwards” that I put in the forwards_func . And then it prints out everything python manage.py loaddata would do with --verbosity=2.

Then when I check the database, I should see 14 records of Rank objects. :D

— — — —

To do a quick check, I’ll modify the Rank schema and see if migrations still works.
I’ll add new field to the Rank. Then run python manage.py makemigrations .

The picture below show that Django can auto-generate migration file called 0045_rank_airmee.py . Cool…

If you want to clear the database to get the fresh clean one, do the following command.

python manage.py reset_db

it drops all tables.

:D

When reverse migration. You can see “reverse” is printed by reverse_func.

You can see the downside of doing loading data at late in timeline, consequence of restoring data back to previous version. I’m feeling lazy while I’m talking now…

--

--