Search code examples
pythonhashuuiddjango-migrations

Adding a HASH column to existing table in Django


I want to add a new HASH column to my existing django table. I referred How to generate HASH for Django model. Here is how I am doing it:

def _create_uuid():
    return uuid.uuid4().hex[:20]
    
class users(models.Model):
    user_id = models.CharField(max_length=100, primary_key=True)
    uuid= models.CharField(max_length=20, null=False, default=_create_uuid)

While this works completely fine for all the new users created after the addition of the uuid column. But all the existing users get assigned with the same uuid in the uuid column when I migrate. I want the existing users to have unique uuid as well. How can I do this?


Solution

  • You could run a Python script during the migration to generate the hashes. Generate a migrations file first with an empty default value. Then add a RunPython function and alter the field to use your _create_uuid default function for new values. The migration script could look like this:

    from django.db import migrations, models
    import YOURPROJECT.YOURAPP.models
    import uuid
    
    def generate_hash(apps, schema_editor):
        User = apps.get_model("YOURAPP", "users")
        users = User.objects.all()
        for u in users:
            u.uuid = uuid.uuid4().hex[:20]
            u.save()
    
    def reverse_generate_hash(apps, schema_editor):
        pass
    
    
    class Migration(migrations.Migration):
    
        dependencies = [
            ('YOUTAPP', 'PREVIOUS_MIGRATIONS_FILE'),
        ]
    
        operations = [
            migrations.AddField(
                model_name='users',
                name='uuid',
                field=models.CharField(default='', max_length=20),
            ),
            migrations.RunPython(generate_hash, reverse_generate_hash),
            migrations.AlterField(
                model_name='users',
                name='uuid',
                field=models.CharField(default=jYOURPROJECT.YOURAPP.models._create_uuid, max_length=20),
            ),
        ]