'Django migrations - how to apply newly applied rules to previously saved model instances?

Let's say I have the following model and I have already some instances of the model saved in the database -

class Comment(models.Model):
    comment_text = models.CharField(max_length=255)

Now, if I want to change the max_length argument to 127 instead of 255 and apply the migrations, the older instances will still be in the database where some might have the length more than 127 which is not obeying the new migrations.

What is the best approach to migrate all previous data along with the new migration rules?



Solution 1:[1]

You have to write your migration and apply that before the generated migration (which alters the model).

For this purpose, you have first to write your migration. Place it in the migrations folder of the app. Then add its name to the dependencies field of the generated migration.

This example updates the uuid field of all MyModel Objects. And is located in my_migration.py

# Generated by Django A.B on YYYY-MM-DD HH:MM
from django.db import migrations
import uuid

def gen_uuid(apps, schema_editor):
    MyModel = apps.get_model('myapp', 'MyModel')
    for row in MyModel.objects.all():
        row.uuid = uuid.uuid4()
        row.save(update_fields=['uuid'])

class MyMigration(migrations.Migration):

    dependencies = [
        ('myapp', '0004_add_uuid_field'),
    ]

    operations = [
        # omit reverse_code=... if you don't want the migration to be reversible.
        migrations.RunPython(gen_uuid, reverse_code=migrations.RunPython.noop),
    ]

Assume that your generated migration that alters MyModel is called GeneratedMigration.. edit the generated migrations file as below.

class GeneratedMigration(migrations.Migration):

    dependencies = [
        ('myapp', 'my_migration'),
    ]

You can also use the run_before attribute.

Checkout djano documentation on writing migrations for more information.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nima Afshar