编程语言
首页 > 编程语言> > python – 使用uuid字段的Django迁移会生成重复的值

python – 使用uuid字段的Django迁移会生成重复的值

作者:互联网

我有一个uuid字段(不是主键).生成的迁移是:

from __future__ import unicode_literals

from django.db import migrations, models
import uuid


class Migration(migrations.Migration):

    dependencies = [
        ....
    ]

    operations = [
        ...
        migrations.AddField(
            model_name='device',
            name='uuid',
            field=models.UUIDField(default=uuid.uuid4, unique=True),
        ),
        ...
    ]

但是在进行python manage.py迁移时,它崩溃了:

django.db.utils.IntegrityError: could not create unique index
“restaurants_device_uuid_key” DETAIL: Key
(uuid)=(f3858ded-b8e0-4ac0-8436-8a61b10efc73) is duplicated.

奇怪的是,主键(它可能是由数据库创建的,而不是由django内部创建的)似乎不会出现问题.

如何添加uuid字段,并确保迁移有效?

解决方法:

这是一个通过RunPython调用在一次迁移中完成所有操作的示例.

# -*- coding: utf-8 -*
from __future__ import unicode_literals

from django.db import migrations, models
import uuid


def create_uuid(apps, schema_editor):
    Device = apps.get_model('device_app', 'Device')
    for device in Device.objects.all():
        device.uuid = uuid.uuid4()
        device.save()


class Migration(migrations.Migration):

    dependencies = [
        ('device_app', 'XXXX'),
    ]

    operations = [
        migrations.AddField(
            model_name='device',
            name='uuid',
            field=models.UUIDField(blank=True, null=True),
        ),
        migrations.RunPython(create_uuid),
        migrations.AlterField(
            model_name='device',
            name='uuid',
            field=models.UUIDField(unique=True)
        )
    ]

标签:python,django,django-migrations,uuid
来源: https://codeday.me/bug/20190930/1836107.html