UUID field added after data already in database. Is there any way to populate the UUID field for existing data?

前端 未结 3 1726
轻奢々
轻奢々 2021-02-04 04:40

I\'ve added a UUID field to some of my models and then migrated with South. Any new objects I create have the UUID field populated correctly. However the UUID fields on all my o

3条回答
  •  温柔的废话
    2021-02-04 05:09

    To add UUID values to all existing records first you will need to make sure your model has the UUID filed with blank=True, null=True

    Then Run the schemamigration command with south and then open up the resulting migration file. And then Edit your migration file with the following as shown in this post

    Quote:

    You'll need to import the following import uuid

    At the end of the forwards() function add the following def forwards(self, orm):

    ...
    for a in MyModel.objects.all():
        a.uuid = u'' + str(uuid.uuid1().hex)
        a.save()
    

    As stated that will loop through existing instances and add a uuid to it as part of the migration.

提交回复
热议问题