Junior — Middle
When is it recommended to use custom migrations instead of standard database migration procedures?
sobes.tech AI
Answer from AI
It is recommended to use custom database migrations in the following cases:
- When standard migration tools do not support the required operations (e.g., complex schema changes that cannot be expressed declaratively).
- When additional actions are needed during migration, such as data transformation, running scripts, or integrating with external systems.
- If more fine-grained control over the order and content of migrations is required.
For example, in Django, you can create custom migrations using RunPython to execute custom code:
from django.db import migrations
def forwards_func(apps, schema_editor):
MyModel = apps.get_model('app_name', 'MyModel')
for obj in MyModel.objects.all():
obj.field = transform(obj.field)
obj.save()
class Migration(migrations.Migration):
dependencies = [('app_name', '0001_initial')]
operations = [migrations.RunPython(forwards_func)]
Thus, custom migrations provide flexibility when working with database changes that are not covered by standard tools.