Django:uuid4中的重复条目

时间:2015-10-19 10:07:36

标签: python mysql django

我在我的表user_table中添加了一个新的uuid字段,其中包含现有行。由于竞争条件,我得到了#34;重复条目"迁移时出错。然后我按照这里的步骤进行操作:

http://django.readthedocs.org/en/latest/howto/writing-migrations.html

现在我的第一次和第二次迁移都在运行,但我上次的迁移给了我同样的错误。我对链接的3次迁移如下:

迁移'标签'

from __future__ import unicode_literals

from django.db import models, migrations
import uuid


class Migration(migrations.Migration):

    dependencies = [
        ('app', '0008_label'),
    ]

    operations = [
        migrations.AddField(
            model_name='user_table',
            name='UUID_loc',
            field=models.UUIDField(default=uuid.uuid4, null=True),
        ),
        migrations.AlterField(
            model_name='another_table',
            name='Time',
            field=models.CharField(default=0, max_length=3),
        ),
    ]

迁移' 0010_label'

from __future__ import unicode_literals

from django.db import migrations, models
import uuid

def gen_uuid(apps, schema_editor):
    MyModel = apps.get_model('app', 'user_table')
    for row in MyModel.objects.all():
        row.uuid = uuid.uuid4()
        row.save()

class Migration(migrations.Migration):

    dependencies = [
        ('app', '0009_label'),
    ]

    operations = [
        # omit reverse_code=... if you don't want the migration to be reversible.
        migrations.RunPython(gen_uuid, reverse_code=migrations.RunPython.noop),
    ]

迁移' 0011_label'

from __future__ import unicode_literals

from django.db import models, migrations
import uuid


class Migration(migrations.Migration):

    dependencies = [
        ('app', '0010_label'),
    ]

    operations = [
        migrations.AlterField(
            model_name='user_table',
            name='UUID_loc',
            field=models.UUIDField(default=uuid.uuid4, unique=True),
        ),

    ]

该链接与我非常相关,但不幸的是我收到同样的错误。现在我被困在这里我的表有UUID_loc字段,但它还不是唯一的,即第三次迁移还没有运行。有人可以提供一些见解吗?谢谢。

1 个答案:

答案 0 :(得分:1)

我认为您应该稍微编辑第二次迁移,以防止django使用重复的uuid值更新模型。

def gen_uuid(apps, schema_editor):
    MyModel = apps.get_model('app', 'user_table')
    for row in MyModel.objects.all():
        while True:
            row.uuid = uuid.uuid4()
            if not MyModel.objects.filter(uuid=row.uuid).exists():
                break

        row.save()

您应该再次重新运行第二次迁移,然后您应该能够毫无问题地运行第三次迁移。