From b682a90938bdafd51c539b1ada356e3cb4ed9b71 Mon Sep 17 00:00:00 2001 From: Parsa Nazer Date: Fri, 5 Dec 2025 14:10:42 +0330 Subject: [PATCH] fix: Ensure unique slug generation for SubCategoryModel --- backend/product/models.py | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/backend/product/models.py b/backend/product/models.py index b31c113..4617358 100644 --- a/backend/product/models.py +++ b/backend/product/models.py @@ -99,8 +99,22 @@ class SubCategoryModel(models.Model): return self.name def save(self, *args, **kwargs): + # Ensure slug is present and unique. If a slug (auto or custom) would + # collide with an existing product, append a numeric suffix. if not self.slug: - self.slug = slugify(self.name, allow_unicode=True) + base_slug = slugify(self.name, allow_unicode=True) + else: + # Normalize a provided slug + base_slug = slugify(self.slug, allow_unicode=True) + + slug_candidate = base_slug + counter = 1 + # Exclude self.pk to allow updating the same instance + while ProductModel.objects.filter(slug=slug_candidate).exclude(pk=self.pk).exists(): + slug_candidate = f"{base_slug}-{counter}" + counter += 1 + + self.slug = slug_candidate super().save(*args, **kwargs)