January 15, 2021 ← Last time: Create Day 9 model
This article is not a single article. I wrote it as a diary, so I think it will be useful for those who are new to it. If you want to learn Django, we recommend reading it from [Day 1] Django Development Environment.
The theme this time is "database migration". Django has a database migration feature. By using this, a table is automatically created in the database based on the created model. If you are familiar with Ruby on Rails, this is a feature you are familiar with.
First, let's migrate the Django standard model.
python
(venv)$ ./manage.py migrete
If you do this, 「OK OK OK It will be displayed like "OK ...". This completes the first migration. At this stage, your own model will not be migrated. You need to run make migrations to migrate your own model.
python
(venv)$ ./manage.py makemigrations
python
Migrations for 'thread':
thread/migrations/0001_initial.py
- Create model Category
- Create model Comment
- Create model Topic
- Add field topic to comment
- Add field user to comment
You should get the above output and you are ready to migrate. Let's check.
python
(venv)$ ./manage.py showmigrations
python
thread
[ ] 0001_initial
You will get output like this. The fact that the inside of [] is empty means that it has not been migrated yet. I think it's a good idea to get in the habit of checking what kind of SQL is executed before migration.
python
(venv)$ ./manage.py sqlmigrate thread 0001
Now you can see the SQL at the time of migration of thread application 0001. Make sure that unintended SQL is not issued. Let's migrate.
python
(venv)$ ./manage.py migrate
It is OK if the output is as follows.
python
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions, thread
Running migrations:
Applying thread.0001_initial... OK
Today is the 10th day. Recently, I'm thinking, "Is it meaningful to write an explanation?" The explanation is explained by the head family, and I don't feel much meaning in what I wrote here. However, as long as I'm actually moving my hand, it seems that I can't understand the reason without the explanation, so I will continue to include the explanation.
See you again
← Last time: Create Day 9 model → Next time: Input of Day 11 initial data