通过避免django模型中的完整性错误保存方法来增加块 [英] Incrementing the slug by avoiding Integrity error in django models save method

查看:107
本文介绍了通过避免django模型中的完整性错误保存方法来增加块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个两个字段的模型如下

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)

在这里,我正在创建一个基于名称字段的插件,我们可以在上面看到

Here i am creating a slug based on the name field as we can see above

所以当我们尝试创建具有名称的发布者已经存在时,模型的 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.

当我们再次尝试使用相同的名称创建新记录时, code>诚信错误将被提升如下

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包含数字(最终像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

所以我想要的是,如果数据库中已经存在title / slug,那么将增加slug中的数字 $ / code

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  

任何人都可以让我知道如何实现上述增加lug above的逻辑?

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模型中的完整性错误保存方法来增加块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆