填充数据库时,Slug错误 - Django

时间:2015-05-17 07:10:21

标签: python django scripting

我是django的新手,目前正在学习基础知识。但是,我坚持使用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

编写模型后,我运行了迁移命令并成功。

现在我的数据库为空,我编写了一个填充脚本(包含虚拟值)来填充我的数据库。

但每当我运行人口脚本时,我都会遇到错误

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

Population.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()

然而,我认为没有一个" slug"人口脚本中的字段给出了此错误。

那么您建议在填充脚本中进行哪些修改以消除此错误?

提前致谢。

1 个答案:

答案 0 :(得分:1)

是的,您应该设置类别的slug字段。如果您不这样做,那么该字段的空值对于第二个类别条目将不是唯一的。

解决此问题的最简单方法是使用slugify()实用程序函数:

from django.utils.text import slugify

def add_cat(name,views,likes):
    defaults={'views': views, 'likes': likes, 'slug': slugify(name)}
    return Category.objects.get_or_create(name=name, defaults=defaults)[0]

UPDATE :要使字符串unicode将u'前缀添加到字符串文字中:

python_cat = add_cat(u'Python', 128, 64)