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.
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
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:
my_project
directory:cd /usercode/my_project
python3 manage.py makemigrations my_app
python3 manage.py migrate
#!/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()
Free Resources