在Django迁移中生成UUID(RunPython)正在生成相同的UUID

时间:2018-06-22 18:33:23

标签: python django database-migration uuid

类似于question here,我正在尝试向具有现有行的数据库表添加唯一的UUID字段。我尝试按照说明进行操作,并将迁移分为3个操作:

def create_user_id(apps, schema_editor):
    User = apps.get_model('authentication', 'User')
    for instance in User.objects.all():
        if not instance.user_id:
            instance.user_id = uuid.uuid4()
            instance.save(update_fields=['user_id'])

class Migration(migrations.Migration):

    dependencies = [
        ('authentication', '0002_auto_20180101_1422'),
    ]

    operations = [
        migrations.AddField(
            model_name='user',
            name='user_id',
            field=models.UUIDField(blank=True, editable=False, null=True),
        ),
        migrations.RunPython(create_user_id),
        migrations.AlterField(
           model_name='user',
           name='user_id',
           field=models.UUIDField(blank=True, default=uuid.uuid4, editable=False, null=True, unique=True),
    )
    ]

但是,我在第三次操作中仍然遇到完整性错误。仔细检查发现,创建的user_id完全相同。可能是什么原因造成的?

0 个答案:

没有答案