Complete worked example
python
from bootstrap_lab import django_setup
django_setup(__name__)
from django.db import connection, migrations, models
from django.db.migrations.state import ProjectState
def migrate_saved_row(country):
if country not in {"US", "IL", "UA"}:
raise ValueError("supported default required")
first = migrations.Migration("initial", "framework_lab")
first.operations = [migrations.CreateModel(name="MigrationRecord", fields=[("id", models.AutoField(primary_key=True)), ("title", models.CharField(max_length=80))])]
second = migrations.Migration("country", "framework_lab")
second.operations = [migrations.AddField(model_name="migrationrecord", name="country", field=models.CharField(max_length=2, default=country), preserve_default=False)]
with connection.schema_editor() as editor:
before = first.apply(ProjectState(), editor)
old_model = before.apps.get_model("framework_lab", "MigrationRecord")
old_model.objects.create(title="Saved")
after = second.apply(before, editor)
model = after.apps.get_model("framework_lab", "MigrationRecord")
row = model.objects.get()
result = {"title": row.title, "country": row.country}
editor.delete_model(model)
return result- Reasoning
- ProjectState supplies the historical model registry used at each step. The first migration creates a title-only table, while the second adds country and supplies a value for its existing row.