Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

python - Django - Slugs - Key (slug)=() is duplicated

just started fooling around with Django and came across a link here on how to create slugs. I was told to perform the following changes to an existing model:

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

This worked out pretty well until I tried to migrate the database using:

python manage.py makemigrations

The above asked for a default value so following the guide, I gave it ''. Then:

python manage.py migrate

The above returned "DETAIL: Key (slug)=() is duplicated."

I'm not entirely sure why this happened. Perhaps it's because I'm adding a new field that is unique and I can't populate it with ''? If so, what do I have to do in order to populate the database?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The documentation explains how to migrate in these circumstances. A quick summary:

  • create the field without unique=True
  • create a migration with a RunPython function that iterates through all Categories and calls save on them, which will populate the slug
  • create a final migration which sets unique=True.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...