Junior — Middle
Have you used custom migration scripts when working with Django?
sobes.tech AI
Answer from AI
Django typically uses its built-in migration system, which automatically generates scripts based on model changes. However, there are times when you need to write custom migration scripts, for example:
- To perform complex database changes that are not supported automatically.
- For data migrations, when you need to transform or transfer data.
An example of a custom data migration:
from django.db import migrations
def forwards_func(apps, schema_editor):
MyModel = apps.get_model('myapp', 'MyModel')
for obj in MyModel.objects.all():
obj.field = transform(obj.field)
obj.save()
class Migration(migrations.Migration):
dependencies = [
('myapp', '0001_initial'),
]
operations = [
migrations.RunPython(forwards_func),
]
Thus, custom migration scripts allow flexible management of changes and data in the database.