Junior — Middle
Do you have experience creating custom migrations in Django for database schema changes?
sobes.tech AI
Answer from AI
Yes, in Django projects I have created custom migrations to manage database changes. Usually, Django automatically generates migrations, but sometimes it is necessary to write a migration manually, for example, for complex changes or data.
Example of creating a custom migration:
- Create a migration file in the migrations folder of your app.
- Define a migration class with
operationsmethods, where you can useRunPythonto execute arbitrary code.
from django.db import migrations
def forwards_func(apps, schema_editor):
MyModel = apps.get_model('myapp', 'MyModel')
MyModel.objects.create(name='Example')
def backwards_func(apps, schema_editor):
MyModel = apps.get_model('myapp', 'MyModel')
MyModel.objects.filter(name='Example').delete()
class Migration(migrations.Migration):
dependencies = [
('myapp', '0001_initial'),
]
operations = [
migrations.RunPython(forwards_func, backwards_func),
]
This approach allows for more flexible migration control, including data modification, not just database structure.