How To Write Custom migrations in Django

Reading Time : ~ .

Migrations are mainly for keeping the data model of your database up-to-date.

Django will never run same migration file more than once on the same database. All this is managed by table named "django_migrations" which gets created when we first apply the migrations. For each migration(file), a new record(row) is inserted into this table.

There are also a few “special” operations of Migration class which can be used to add our custom migrations.

RunSQL

This allows us to execute raw SQL.

Example:

from __future__ import unicode_literals
from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ...
        dependencies goes here
    ]

    operations = [
        migrations.RunSQL("INSERT INTO product (title) VALUES ('Product1');"),
    ]

RunPython

This can be used to run custom Python code. Here code should be separate function that accepts two arguments - first is an instance of django.apps.registry.Apps containing historical models that match the operation’s place in the project history, and the second is an instance of SchemaEditor.

Example:

from __future__ import unicode_literals
from django.db import migrations


def create_countires(apps, schema_editor):
    Country = apps.get_model("app_name", "Country")
    Country.objects.bulk_create([
        Country(name="India"),
        Country(name="USA"),
    ])


class Migration(migrations.Migration):

    dependencies = [
        ...
        dependencies goes here
    ]

    operations = [
        migrations.RunPython(create_countires),
    ]

Once we have the function we can call it from our RunPython operation and then this function will be executed when we run ./manage.py migrate from the command line.

This can be also be used in case if you want to copy few columns data from one table to another table before removing those columns from first table.

After creating a new table, add this custom migration file to copy existing data to new table.

from __future__ import unicode_literals
from django.db import migrations, models


def create_objects(apps, schema_editor):
    Table1 = apps.get_model("test_app", "Table1")
    Table2 = apps.get_model("test_app", "Table2")
    table2_objects = []
    for obj_table1 in Table1.objects.all():
        table2_objects.append(
            Table2(column1=obj_table1.column1, column2=obj_table1.column5)
        )
    Table2.objects.bulk_create(table2_objects)


class Migration(migrations.Migration):

    dependencies = [
        ...
        dependencies goes here
    ]

    operations = [
        migrations.RunPython(create_objects),
    ]

After creating this migration, you can now remove unused columns from table1 and run makemigrations.

Note: While adding this custom migrations, you must load the model using apps.get_model() method as you run migrations, your model can change. For example, a field can be added or removed in a subsequent migration.

    By Posted On
SENIOR DEVELOPER at MICROPYRAMID

Need any Help in your Project?Let's Talk

Latest Comments
Related Articles
Deploying Your Django app on Heroku Swetha Naretla

Heroku is a platform as a service (PaaS) that enables developers to build and run applications entirely in the cloud.
1. installation
2. Creating and ...

Continue Reading...
What's great about Django girls to inspire women into programming Vinisha Naladala

Django girls is a non-profit organization, that helps women to learn Django programming language and to inspire them into programming. They are organizing workshops all ...

Continue Reading...
Overriding Django Model behaviour with Proxy Model Ravi Kumar Gadila

The main Usage of a proxy model is to override the main functionality of existing Model. It is a type of model inheritance without creating ...

Continue Reading...

Subscribe To our news letter

Subscribe to our news letter to receive latest blog posts into your inbox. Please fill your email address in the below form.
*We don't provide your email contact details to any third parties