一尘不染

django.db.utils.IntegrityError:唯一约束失败:rango_category__new.slug

django

我正在使用Django从Tango中学习Django,但是在输入时,我始终收到此错误:

python manage.py makemigrations rango
python manage.py migrate

这是输出:

django.db.utils.IntegrityError: UNIQUE constraint failed: rango_category__new.slug

Models.py:

from django.db import models
from django.template.defaultfilters import slugify

class Category(models.Model):
    name = models.CharField(max_length=128, unique=True)
    views = models.IntegerField(default=0)
    likes = models.IntegerField(default=0)
    slug = models.SlugField(unique=True)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(Category, self).save(*args, **kwargs)

    def __unicode__(self):
        return self.name


class Page(models.Model):
    category = models.ForeignKey(Category)
    title = models.CharField(max_length=128)
    url = models.URLField()
    views = models.IntegerField(default=0)

    def __unicode__(self):
        return self.title

阅读 1133

收藏
2020-03-31

共1个答案

一尘不染

造成这种限制的原因可能是,在你最初迁移它时,slugCategory类中没有任何字段被调用(第一次迁移),并且在模型中添加了该字段之后,当你运行时makemigrations,你已将默认值设置为静态值值(即None或”等),并且打破了类别表的表段列的唯一约束,其中表段应该是唯一的,但这不是因为所有条目都将获得该默认值。

为了解决这个问题,你可以删除数据库和迁移文件并重新运行makemigrationsmigrate或者设置唯一的默认值,如下所示:

slug = models.SlugField(unique=True, default=uuid.uuid1)

编辑:
根据添加唯一字段的迁移,修改你的迁移文件以克服唯一约束。例如,修改你的迁移文件(将slug字段添加到模型中)如下:

import uuid
from app.models import Category  #where app == tango_app_name

class Migration(migrations.Migration):

    dependencies = [
        ('yourproject', '0003_remove_category_slug'),
    ]

    def gen_uuid(apps, schema_editor):
        for row in Category.objects.all():
            row.slug = uuid.uuid4()
            row.save()

    operations = [
        migrations.AddField(
            model_name='category',
            name='slug',
            field=models.SlugField(default=uuid.uuid4),
            preserve_default=True,
        ),
        migrations.RunPython(gen_uuid),

        migrations.AlterField(
            model_name='category',
            name='slug',
            field=models.SlugField(default=uuid.uuid4, unique=True),
        ),
    ]
2020-03-31