将模型slug字段迁移到现有数据库的唯一

时间:2015-05-04 08:51:36

标签: python django django-models django-migrations

在旧数据库中,slug字段不是唯一的,因此创建了重复项。现在我想迁移slug字段unique = True。

slug = models.CharField(max_length=255, unique=True)

$ python manage.py migrate

django.db.utils.IntegrityError: (1062, "Duplicate entry 'some-x-slug' for key 'some_model_slug_6c7ae6ae040a5e98_uniq'")

如果django检测到重复的slug,我想在迁移时,我想在object_id字段的末尾添加slug,以使该slug唯一。

对于上述问题是否有任何简单的解决方案

1 个答案:

答案 0 :(得分:4)

使用以下RunPython操作更新迁移应该足够了。关注this Django guide on writing migrations以获取推理和更多示例。

your_new_migration.py

def update_slugs(apps, schema_editor):
    SomeModel = apps.get_model("some_app", "SomeModel")

    for instance in SomeModel.objects.all():
        instance.slug = '%s-%s' % (instance.slug, instance.object_id)
        instance.save()


class Migration(migrations.Migration):

    dependencies = [
        # ... your existing dependencies
    ]

    operations = [
        # add this operation ...
        migrations.RunPython(update_slugs, reverse_code=migrations.RunPython.noop),

        # ... before your original migration, such as:
        # migrations.AlterField(
        #     model_name='somemodel',
        #     name='slug',
        #     field=models.CharField(unique=True),
        # ),
    ]