Django Database Migrations

In Django, migration is the process of managing database schema changes. Whenever you make changes to your models, such as adding a new field or modifying an existing one, you need to create a migration to apply these changes to your database.

To create a new migration, you can use the makemigrations command. This command inspects the changes you have made to your models and creates a new migration file that contains the necessary SQL commands to update the database schema.

For example, let's say you added a new field to your models.py file:


class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100)
    published_date = models.DateField()
    rating = models.IntegerField()
 

To create a migration for this change, you can run the following command:


python manage.py makemigrations

This will create a new migration file in the migrations directory with the necessary SQL commands to add the new rating field to the books table in the database.

Once you have created a migration, you can apply it to the database using the migrate command:


python manage.py migrate

This command runs all pending migrations and updates the database schema accordingly.

Django also provides other useful commands for working with migrations, such as showmigrations to display the status of migrations, sqlmigrate to display the SQL statements for a specific migration, and migrate --fake to mark a migration as applied without actually running the SQL commands.

Comments

Leave a Reply