fix: Ensure unique slug generation for SubCategoryModel

This commit is contained in:
Parsa Nazer
2025-12-05 14:10:42 +03:30
parent 68368fc531
commit b682a90938
+15 -1
View File
@@ -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)