In Django, migrations are used to manage changes to your database schema over time. They allow you to propagate changes made to your models (such as adding a new field or modifying an existing one) to your database in a structured and organized way. Here's a step-by-step guide on how to create and apply migrations in Django:
If you don't have a Django project yet, you can create one using the following command:
bashdjango-admin startproject yourprojectname
Navigate to your project folder and create a Django app using the following command:
bashpython manage.py startapp yourappname
Edit the models.py
file in your app to define your models. For example:
python# yourappname/models.py
from django.db import models
class YourModel(models.Model):
name = models.CharField(max_length=255)
age = models.IntegerField()
Run the following commands to create an initial migration:
bashpython manage.py makemigrations
This command analyzes your models and creates a set of migration files in the migrations
directory of your app.
Apply the migrations to the database using the following command:
bashpython manage.py migrate
This command executes the SQL statements defined in the migration files to update the database schema.
If you make changes to your models, update the models.py
file accordingly.
Generate new migrations based on your model changes:
bashpython manage.py makemigrations
Apply the new migrations:
bashpython manage.py migrate
To view the list of migrations and their status:
bashpython manage.py showmigrations
To roll back migrations:
bashpython manage.py migrate yourappname <migration_name>
To fake migrations without running them:
bashpython manage.py migrate --fake
These are the basic steps for creating and applying migrations in Django. Make sure to consult the Django documentation for more advanced use cases and additional migration options.