![]() |
VOOZH | about |
Django’s Object-Relational Mapper (ORM) simplifies database interactions by mapping Python objects to database tables. A key feature of the ORM is migrations, which enable seamless management of changes to the database schema over time.
Migrations are files that store instructions about how to modify the database schema. These files help ensure that the database is in sync with the models defined in the Django project. Whenever changes are made to models, such as adding, modifying, or deleting fields, Django uses migrations to apply these changes to the database.
Commands:
The makemigrations command generates migration files that describe changes to the database schema in Python code.
How It Works:
When python manage.py makemigrations is run, Django detects changes in the models and generates migration files.
After creating migration files using makemigrations, the migrate command applies these changes to the database.
How It Works:
The python manage.py migrate command applies the changes in the correct order by reading the migration files generated by makemigrations. It handles:
Consider a project named ‘geeksforgeeks’ having an app named ‘geeks’. After setting up the project and app, let’s define a model and use migrations to update the database accordingly.
Let’s generate migration files for our new model:
python manage.py makemigrations
Django will create a migration file (e.g., 0001_initial.py) that includes the instructions to create the GeeksModel table in the database.
To apply the migration and create the table in the database, run the following command:
python manage.py migrate
After running makemigrations and migrate, a new table is created in the database. The migration file (geeks/migrations/0001_initial.py) shows the planned database operations. The actual table is created in the database after running the migrate command.
After running makemigrations, Django automatically generates migration files that describe the changes made to the database schema. As an example, Django generates a migration file 0001_initial.py for the GeeksModel, which could look like this:
This file includes: