通过避免 django 模型保存方法中的完整性错误来增加 slug [英] Incrementing the slug by avoiding Integrity error in django models save method
问题描述
我有一个包含两个字段的模型,如下所示
I have a model with two fields as below
models.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,正如我们在上面看到的那样
Here i am creating a slug based on the name
field as we can see above
所以当我们尝试用name已经存在
创建发布者时,模型的save
方法会在末尾添加_1
.
So when we try to create a publisher with name already exists
, the save
method of the model will add the _1
to the end.
当我们再次尝试使用相同的 name
创建新记录时,将引发 Integrity
错误,如下所示
And when we again try to create a new record with same name
, an Integrity
error will be raised as below
>> 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
),我们应该增加它的数字
So what i am want is if the title/slug already exists in the database and if slug contains number in it(at the end like abc_1
), we should increment it that number
所以我想要的只是增加 slug 中的数字
如果标题/slug 已经存在于数据库中
So what all i want is to increment the number in the slug
as below if the title/slug already exists in the database
abc
abc_1
abc_2
abc_3
那么谁能告诉我如何实现上述增加 slug 的逻辑?
So can anyone please let me know how to implement the above logic of incrementing the slug ?
提前致谢......
推荐答案
你将不得不使用循环而不是一个单一的条件.试试这个:
You will have to use loop instead of just a one condition. Try this:
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)
这篇关于通过避免 django 模型保存方法中的完整性错误来增加 slug的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!