0

我是 django 新手,目前正在学习基础知识。但是,我坚持使用 slug 模块。

希望能找到解决办法。提前致谢。

运行迁移命令时

python manage.py makemigrations rango
python manage.py migrate

我不断收到此错误:

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

模型.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

该教程说“由于我们没有为 slug 提供默认值,并且我们已经在模型中拥有现有数据,因此迁移命令将为您提供两个选项。选择提供默认值的选项,然后输入 ''。不要担心这会很快更新。现在重新运行“populate.py”脚本。由于每个类别都调用了 save 方法,因此将执行覆盖的 save 方法,更新 slug 字段。运行服务器,并检查数据通过管理界面在模型中。” (教程的链接在底部的第 3 点中提到)

填充.py 文件

import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'kiran_blog_project.settings')

import django
django.setup()

from exodus.models import Category, Page


def populate():
    python_cat = add_cat('Python',128,64)

    add_page(cat=python_cat,
        title="Official Python Tutorial",
        url="http://docs.python.org/2/tutorial/",views=20)

    add_page(cat=python_cat,
        title="How to Think like a Computer Scientist",
        url="http://www.greenteapress.com/thinkpython/", views=19)

    add_page(cat=python_cat,
        title="Learn Python in 10 Minutes",
        url="http://www.korokithakis.net/tutorials/python/",views=17)

    django_cat = add_cat("Django",64,32)

    add_page(cat=django_cat,
    title="Official Django Tutorial",
    url="https://docs.djangoproject.com/en/1.5/intro/tutorial01/",views=30)

    add_page(cat=django_cat,
        title="Django Rocks",
        url="http://www.djangorocks.com/",views=21)

    add_page(cat=django_cat,
        title="How to Tango with Django",
        url="http://www.tangowithdjango.com/",views=50)

    frame_cat = add_cat("Other Frameworks",32,16)

    add_page(cat=frame_cat,
        title="Bottle",
        url="http://bottlepy.org/docs/dev/",views=13)

    add_page(cat=frame_cat,
        title="Flask",
        url="http://flask.pocoo.org",views=16)

    # Print out what we have added to the user.
    for c in Category.objects.all():
        for p in Page.objects.filter(category=c):
            print "- {0} - {1}".format(str(c), str(p))

def add_page(cat, title, url, views):
    p = Page.objects.get_or_create(category=cat, title=title)[0]
    p.url=url
    p.views=views
    p.save()
    return p

def add_cat(name,views,likes):
    c = Category.objects.get_or_create(name=name)[0]
    c.views=views
    c.likes=likes
    c.save()
    return c

# Start execution here!
if __name__ == '__main__':
    print "Starting  population script..."
    populate()

所以我的问题是,

1.选择提供默认值的选项后,我应该输入什么值?

2.指令还指出,我需要运行“populate.py”文件。但是在运行这个文件之前,我想我需要包含 slug 字段。那么有人可以在“populate.py”字段中指定更改吗?

3.我的django教程链接

4.同一个查询的解决方案,我什至用 uuid 尝试了答案,但没有成功。

4

1 回答 1

3

您必须更改迁移文件以避免独特的约束。根据此指令,修改您的最后一个迁移文件(将 slug 字段添加到模型中),如下所示:

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

迁移文件:(即0004_category_slug.py:)

class Migration(migrations.Migration):

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

    def gen_slug(apps, schema_editor):
        for row in Category.objects.all():
            row.slug = slugify(row.name)
            row.save()

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

        migrations.AlterField(
            model_name='category',
            name='slug',
            field=models.SlugField(default=uuid.uuid4, unique=True),
        ),
    ]
于 2015-05-17T20:41:03.827 回答