4

我有一个具有以下两个字段的模型

模型.py

class Publisher(models.Model):
    name = models.CharField(max_length=200)
    slug = models.SlugField(max_length=150, unique=True)    

    def save(self, *args, **kwargs):
        if not self.id and not self.slug:
            slug = slugify(self.name)
            try:
                slug_exits = Publisher.objects.get(slug=slug)
                if slug_exits:
                    self.slug = slug + '_1'
            except Publisher.DoesNotExist:
                self.slug = slug
        super(Publisher, self).save(*args, **kwargs)

在这里,我正在创建一个基于name字段的 slug,正如我们在上面看到的

因此,当我们尝试使用 来创建发布者时name already exists,模型的save方法将_1在末尾添加 。

当我们再次尝试创建一个相同的新记录时nameIntegrity将引发如下错误

>> Publisher.objects.create(name="abc")
   result: slug will be "abc"
>> Publisher.objects.create(name="abc")
   result: slug will be "abc_1"
>> Publisher.objects.create(name="abc")
   result: 

     .................
     .................
     34     del cursor
     35     del connection
---> 36     raise errorclass, errorvalue
     37 
     38 re_numeric_part = re.compile(r"^(\d+)")

IntegrityError: (1062, "Duplicate entry 'abc_1' for key 'slug'")

所以我想要的是如果标题/slug 已经存在于数据库中,并且如果 slug 包含数字(最后像 abc _1),我们应该增加它的数字

所以如果数据库中已经存在标题/slug,我想要的只是increment the number in the slug 如下

abc
abc_1
abc_2
abc_3  

那么任何人都可以让我知道如何实现上述增加 slug 的逻辑吗?

提前致谢......

4

1 回答 1

5

您将不得不使用循环而不是仅使用一个条件。尝试这个:

class Publisher(models.Model):
    name = models.CharField(max_length=200)
    slug = models.SlugField(max_length=150, unique=True)    

    def save(self, *args, **kwargs):
        if not self.id and not self.slug:
            slug = slugify(self.name)
            slug_exists = True
            counter = 1
            self.slug = slug
            while slug_exists:
                try:
                    slug_exits = Publisher.objects.get(slug=slug)
                    if slug_exits:
                        slug = self.slug + '_' + str(counter)
                        counter += 1
                except Publisher.DoesNotExist:
                    self.slug = slug
                    break
        super(Publisher, self).save(*args, **kwargs)
于 2013-08-12T08:16:09.760 回答