So I have this Django installation in which there are a bunch of migration scripts. They look like so:
00001_initial.py
00002_blah_blah.py
00003_bleh_bleh.py
Now I know these are "database building" scripts which will take stuff defined in file models.py and run them against the database to "create" tables and stuff.
I want to create a new table (so I created its definition in file models.py). For this, I have copied another model class and edited its name and fields, and it is all fine. Let’s call this new model class 'boom'.
How do I "create" this boom table using the migration script and the boom model?
I am worried that I might accidentally disrupt anything that is already in the database. How do I run the migration to create only the boom table? How do I create a migration script specifically for it?
I know that it has something to do with manage.py and running migrate or runmigration (or is it sqlmigrate?...I’m confused). While creating the boom table, I don’t want the database to go boom if you know what I mean :)
First, create a backup of your database. Copy it to your development machine. Try things out on that. That way it doesn't matter if it does go "boom" for some reason.
The first thing to do is
python manage.py showmigrations
This shows all the existing migrations, and it should show that they have been applied with an [X].
Then,
python manage.py makemigrations
Makes a new migration file for your new model (name 00004_...).
Then do
python manage.py migrate
to apply it. To undo it, go back to the state of migrations 00003, with
python manage.py migrate <yourappname> 00003
There are two steps to migrations in Django.
./manage.py makemigrations
will create the migration files that you see. These describe the changes that should be made to the database.
You also need to run
./manage.py migrate
This will apply the migrations and actually run the alter table commands in SQL to change the actual database structure.
Generally, adding fields or tables won't affect anything else in the database. Be more careful when altering or deleting existing fields as that can affect your data.
The reason for two steps is so that you can make changes on a dev machine and once happy commit the migration files and release to your production environment. Then you run the migrate command on your production machine to bring the production database to the same state as your development machine (there isn’t any need for makemigrations in production, assuming that your databases started the same).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With