Django: Custom migration with 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 inmanagement 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 themanagement/commands
directory of your app, inheriting from thedjango.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:
code
: Function that we want to run whendo migration
.reverse_code
: Function that will run when wereverse this migration
.
(Should be defined because it will not allow to reverse if migration file contain RunPython operation that not definereverse_code
).
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
If you think it’s useful for you, just clap your hands 👏 to be encouraged me.
GRASSROOT ENGINEER 😘
Reference:
https://docs.djangoproject.com/en/4.1/ref/migration-operations/#runpython
notion: Django Tips