我正在向模型添加一个新字段:
class Abc(models.Model):
...
slug = models.SlugField(unique=True)
在 Makemigrations
期间,我一次性提供了一个空字符串。然后 Migrate
由于重复键 Key (slug)=() is duplicated
而失败。
以下是我尝试解决的问题。 makemigrations
一切正常,但 migrate
由于同样的原因失败。
1) 移除unique=True
并再次迁移
2)去掉slug字段,重新迁移
3) 设置unique=False
并再次迁移
数据库无法删除。我被困住了,别无选择。有什么建议吗?
最佳答案
您遇到此问题是因为表中至少有两条记录具有相同的 slug。
要解决这个问题,您可以执行以下步骤
- 创建数据迁移。
./manage.py makemigrations <app_name> --empty
在迁移文件中,添加django迁移的
RunPython
文件中的操作。一个例子类似于下面的代码片段。from __future__ import unicode_literals from django.db import models, migrations from django.utils.text import slugify def forwards(apps, schema_editor): Abc = apps.get_model('app', 'Abc') for obj in Abc.objects.all(): if len(obj.slug) == 0: obj.slug = slugify(obj.field1) obj.save() class Migration(migrations.Migration): dependencies = [ ('app', '0003_Abc'), ] operations = [ migrations.RunPython(forwards, reverse_code=migrations.RunPython.noop), ]
添加
unique=True
到现场。创建迁移。
./manage.py makemigrations <app_name>
迁移您的数据库。
./manage.py migrate <app_name>
关于Django 模型 : adding a new field with unique=True and migrate will fail due to entering a same value to existing records,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31064863/