In Django, migrations are used to manage changes to the database schema. These changes could include creating new tables, adding or removing fields from existing tables, and updating the data in the tables. Migrations are created using the command line tool makemigrations
and are applied using the command migrate
.
Django automatically creates migration files for changes made to models using the built-in ORM but you can also create custom migration files to perform more complex operations like adding a new field to an existing table or running custom SQL statements.
Django create custom migration file:
- First, run the following command to create an empty migration file inside the myapp:
# django create empty migration
python manage.py makemigrations myapp --empty
- In the new migration file, import the necessary modules from Django by adding the following lines at the top of the file:
from django.db import migrations
- This is a migration class that inherits from
migrations.Migration
and adds adependencies
attribute that lists any other migration files that need to be run before this one. Such asRunSQL
django migrations
class Migration(migrations.Migration):
dependencies = [
('app_name', '0001_initial.py'),
]
- Define the
operations
attribute as a list of migration operations. These operations include methods such asRunSQL
,RunPython
,AddField
,RemoveField
etc.
How do I execute raw SQL in a django migration?
# django custom migration operation
operations = [
#django migrations runsql example
migrations.RunSQL("ALTER TABLE myapp_mymodel ADD COLUMN myfield VARCHAR(255)"),
# django migrations runpython
migrations.RunPython(custom_function),
#django migrations addfield example
migrations.AddField(
model_name='mymodel',
name='new_field',
field=models.CharField(default='default value', max_length=255),
#django migrations addfield example
migrations.RemoveField(
model_name='mymodel',
name='field_to_remove',
),
]runsql django
- Create a custom function if you are using
RunPython
operation
def custom_function(apps, schema_editor):
MyModel = apps.get_model('myapp', 'MyModel')
#django migration insert data
for obj in MyModel.objects.all():
obj.myfield = "default value"
obj.save()
- The final migration file will be as:
- Run the Django migrate command:
#django migrate specific migration
python manage.py migrate
myapp 0002
Note: You can also create your custom migration file app/migrations/000X_custommigration.py
(X will be a serial number) and then modify the migration file to include your custom operations.
The Short Note:
This is a basic example of creating a custom migration file in Django. You can also use other migration operations such as AddField
, RemoveField
, RenameField
, AddConstraint
, RemoveConstraint
, etc. depending on your needs.
Related tutorial: How to create custom model fields in Django