Question

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

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.

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'")

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

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  

So can anyone please let me know how to implement the above logic of incrementing the slug ?

Thanks in advance......

Was it helpful?

Solution

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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top