0

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?

1
  • Don't you need to use brackets the default function =_create_uuid()? Commented Nov 14, 2020 at 9:58

1 Answer 1

0

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),
        ),
    ]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.