Is it possible to leverage a catch exception for a pre_save signal?

Viewed 46

I have a simple "before create" lifecycle hook/django signal.

class Item(models.Model):
    title = CharField()
    slug = CharField(unique=True)
    
    @hook(BEFORE_CREATE):
    def populate_slug(self):
        slug = slugify(self.title)
        n = 1
        while Item.objects.filter(slug=(f"${slug}-${n}")).exists():
            n += 1
        self.slug = f"${slug}-${n}"

Is it possible to save that additional .exists() query and somehow leverage a IntegrityError exception error (as the slug has unique=True) to update the slug?

Something like:

@hook(BEFORE_CREATE):
def populate_slug(self):
    for i in range(0,100):
        slug = slugify(self).title
        n = 1
        while True:
            try:
                self.slug = f"${slug}-${n}"
                # This defeats the purpose of using
                # a "before create" signal though
                self.save()
            except:
                n += 1
                continue
            break

            
0 Answers
Related