Django: Custom migration with RunPython

Grassroot Engineer
3 min readFeb 5, 2023

--

https://docs.djangoproject.com/en/4.1/ref/migration-operations/#runpython

What is RunPython?

  • It’s a method in migration operation in Django
  • Use for running a specific function when migrate

When & Why should use it?

  • When want to populate/edit data in database that related to the migration will make.
  • It’s may seem better than create a management command because
    a. Management command leave an unused code after we run it for only one time.
    b. Easy to keep record or tracking what we changed anything in db because it’s still stay in migration scripts, not like in management command will harder for tracking.
  • Basically it is approach of custom migration that related to database.

Django management commands are custom commands that can be run from the command line, they are a convenient way to automate tasks in your Django project. They allow you to perform actions such as creating database tables, populating the database with data, and more. They can be created by defining a class in the management/commands directory of your app, inheriting from the django.core.management.base.BaseCommand class.

This is sample of management/commands
- We will extend from BaseCommand in Django
- When need to execute will call file name like command in photo below
(green highlight)

When we are using RunPython in migration file we need to define 2 parameters:

  1. code: Function that we want to run when do migration.
  2. reverse_code: Function that will run when we reverse this migration.
    (Should be defined because it will not allow to reverse if migration file contain RunPython operation that not define reverse_code).
Example of used case for RunPython()

Example of Another case that I need to use RunPython() to solve step by step explaination.

Ref: https://docs.djangoproject.com/en/dev/howto/writing-migrations/#migrations-that-add-unique-fields

This picture to show error of duplication.
Then we will create empty 2 migration files.
This is steps to solve by custom 3 migration files. (RunPython.noop means if doing reverse migration will do nothing)
Finally we can migrate as usual and got unique uuid in db.

If you think it’s useful for you, just clap your hands 👏 to be encouraged me.

GRASSROOT ENGINEER 😘

--

--