How to run migrations in Django

Migrations in Django are a way to apply changes to the database schema. To elaborate, they allow us to track any sort of changes and modifications made to our models, i.e., creations of new tables as well as their alteration.

Running migrations

To run migrations, we need to enter the following commands in our Django app:

  • Firstly, we run the following command:

    python3 manage.py makemigrations <your_app_name>
    

    In the code above, Django analyzes the changes made in the models and creates a migrations file based on those changes.

  • Secondly, we run the following command to apply the migrations we just made, i.e., synchronize the database schema with the current state of the models:

    python3 manage.py migrate
    

Coding example

In the coding example below, there is a table named sampleTable, which we will migrate.

To get the hang of how to apply migrations in Django, follow these steps:

  • Step 1: Click the “Run” button below. This will open up a terminal.
  • Step 2: Enter the following command to go to the my_project directory:
    cd /usercode/my_project
    
  • Step 3: Enter the following command in the terminal to create migration files:
    python3 manage.py makemigrations my_app
    
  • Step 4: Enter the following command in the terminal to apply the migrations:
    python3 manage.py migrate
    

Code

#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys


def main():
    """Run administrative tasks."""
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_project.settings")
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)


if __name__ == "__main__":
    main()
Running migrations in Django

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved