django migrations example

Django Migrations Example

By Daniel Williams
AD

Django migrations are a powerful feature of the Django framework that allow you to evolve your database schema over time. They provide a way to manage changes to your models, ensuring that your database schema stays in sync with your code. In this guide, we will explore Django migrations through an example, illustrating the process from creating a migration to applying it to your database.

Before we dive into the example, let's briefly understand why Django migrations are important. Django migrations help manage your database schema modifications efficiently, ensuring that your application's database is always up-to-date with the latest model definitions. They also allow multiple developers to work on the same project without stepping on each other's toes when making database schema changes.

Creating a Migration

Let's say we have a simple Django application with a 'Book' model, and we want to add a new field 'rating' to represent the book's rating. First, we need to create a new migration with the changes. We can do this using the following command:

AD
Database Migration in Django
Database Migration in Django
Django Request-Response Cycle
Django Request-Response Cycle
a flow diagram with several different types of web pages and the text below it is in green
a flow diagram with several different types of web pages and the text below it is in green

`python manage.py makemigrations`

This command analyzes your models and compares them to the current state of your database, generating new migration files based on the differences. These migration files are Python scripts that contain the SQL statements needed to modify your database schema.

Django Project Structure Explained (Beginner Guide)
Django Project Structure Explained (Beginner Guide)
🔗 Django Models: OneToOneField (One-to-One Relationship)
🔗 Django Models: OneToOneField (One-to-One Relationship)
10 DJANGO PROJECTS EVERY PYTHON DEVELOPER SHOULD BUILD
10 DJANGO PROJECTS EVERY PYTHON DEVELOPER SHOULD BUILD

Migration Files

When you run `makemigrations`, Django creates two new files in the `migrations` directory of your app: `0002_{filename}.py` and `0002_alter_{table_name}.py`. The first file contains the SQL statements to create the new field, while the second file contains the statements to update the existing data.

Here's an example of what the generated migration files might look like:

AD

`0002_books.py`

how does python django framework work? infographical poster on black background with white text
how does python django framework work? infographical poster on black background with white text
DJANGO ROADMAP (2026)
DJANGO ROADMAP (2026)
the menu for an italian restaurant, with instructions on how to order and what to eat
the menu for an italian restaurant, with instructions on how to order and what to eat
a diagram showing the flow of user and user views
a diagram showing the flow of user and user views
Django Static Files Made Simple
Django Static Files Made Simple
a flow diagram with different types of data and information in it, including the text
a flow diagram with different types of data and information in it, including the text
```python from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('myapp', '0001_initial'), ] operations = [ migrations.AddField( model_name='book', name='rating', field=models.IntegerField(default=0), ), ] ```

`0002_alter_books.py`

```python from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('myapp', '0002_books'), ] operations = [ migrations.AlterField( model_name='book', name='rating', field=models.IntegerField(default=5), ), ] ```

Applying Migrations

Now that we have our migration files, we can apply them to our database using the `migrate` command:

AD

`python manage.py migrate`

a poster with the names and numbers of different types of animals in it's habitat
a poster with the names and numbers of different types of animals in it's habitat

This command runs through each migration file, applying the changes to your database in the order they were created. If you want to skip the automatic creation of migration files and just apply the changes, you can use `schemamigration` followed by the name of your app:

`python manage.py schemamigration myapp --initial`

AD

This command creates migration files for every change made to your models and applies them all at once. This is useful when you're just starting a new project or when you want to reset your database to the latest schema.

Reversing Migrations

Sometimes, you might need to undo a migration. Maybe you added a field by mistake, or maybe you want to roll back a change to a previous version of your app. Django makes this easy with its migration history tracking. Each migration file has a `Migratio`n class with `dependencies` and `operations` attributes, which allow Django to keep track of the order in which migrations were applied.

To reverse a migration, simply run `manage.py migrate {app_name} {migration_file_name} zero`:

`python manage.py migrate myapp 0002_books zero`

This command undoes the changes made in the specified migration file, rolling your database schema back to the state it was in before that migration was applied.

Migration Strategies

Django provides several strategies for applying migrations to your database. The most common strategy is `migrate`, which applies migrations in the order they were created. Other strategies include `run`, which only applies the migrations that are relevant to the current app, and `fake`, which records that migrations have been applied without actually making any changes to your database.

To apply migrations using a specific strategy, use the `--strategy` option with the `migrate` command:

`python manage.py migrate --strategy=run myapp`

For more information on available strategies, see the Django documentation on migration strategies.

In the rapidly evolving landscape of web development, Django migrations provide a crucial tool for managing changes to your database schema. By understanding and leveraging Django migrations, you can ensure that your application's database is always in sync with your models, making your development process smoother and more reliable.

AD