Note that there are some explanatory texts on larger screens.

plurals
  1. POIncrementing the slug by avoiding Integrity error in django models save method
    primarykey
    data
    text
    <p>I have a model with two fields as below</p> <p><strong>models.py</strong></p> <pre><code>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) </code></pre> <p>Here i am creating a slug based on the <code>name</code> field as we can see above</p> <p>So when we try to create a publisher with <code>name already exists</code>, the <code>save</code> method of the model will add the <code>_1</code> to the end.</p> <p>And when we again try to create a new record with same <code>name</code>, an <code>Integrity</code> error will be raised as below</p> <pre><code>&gt;&gt; Publisher.objects.create(name="abc") result: slug will be "abc" &gt;&gt; Publisher.objects.create(name="abc") result: slug will be "abc_1" &gt;&gt; Publisher.objects.create(name="abc") result: ................. ................. 34 del cursor 35 del connection ---&gt; 36 raise errorclass, errorvalue 37 38 re_numeric_part = re.compile(r"^(\d+)") IntegrityError: (1062, "Duplicate entry 'abc_1' for key 'slug'") </code></pre> <p>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<code>_1</code>), we should increment it that number</p> <p>So what all i want is to <code>increment the number in the slug</code> as below if the title/slug already exists in the database</p> <pre><code>abc abc_1 abc_2 abc_3 </code></pre> <p>So can anyone please let me know how to implement the above logic of incrementing the slug ?</p> <p>Thanks in advance......</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload