Django Migrations#

https://docs.djangoproject.com/en/4.0/topics/migrations/#

Dimension with Data Migration#

Given a simple Dimension model with key and value:

class Dimension(models.Model):
    key = models.TextField()
    value = models.IntegerField()

    class Meta:
        db_table = 'dim_something'
        verbose_name = 'Dimension'
        verbose_name_plural = 'Dimensions'

    def __str__(self):
        return self.key

First create a new data migration:

./manage.py makemigrations --empty --name dimension app

… and add the following boilerplate code:

from django.db import migrations


VALUES = {
    'Alpha': 1,
    'Beta': 1,
}


def forward(apps, schema_editor):
    Dimension = apps.get_model('myapp', 'Dimension')
    for key, value in VALUES.items():
        Dimension.objects.create(key=key, value=value)


def backward(apps, schema_editor):
    Dimension = apps.get_model('myapp', 'Dimension')
    Dimension.objects.filter(name__in=VALUES.keys()).delete()


class Migration(migrations.Migration):
    dependencies = [
        # ...
    ]

    operations = [
        migrations.RunPython(forward, backward),
    ]

Bemerkung

We use apps.get_model(app_label, model_name) to get the model class instance. This allows Django to use historical models.

Further reading in the official documentation.