Skip to content

Commit

Permalink
fix: update model and migration
Browse files Browse the repository at this point in the history
  • Loading branch information
happychuks committed Dec 11, 2024
1 parent 5f833bf commit 6ec47b2
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 6 deletions.
15 changes: 11 additions & 4 deletions server/apps/research/migrations/0016_category_slug.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,17 @@

def remove_duplicate_slugs(apps, schema_editor):
Category = apps.get_model('research', 'Category')
duplicate_slugs = Category.objects.values('slug').annotate(count=models.Count('slug')).filter(count__gt=1)
for slug in duplicate_slugs:
Category.objects.filter(slug=slug['slug']).exclude(id=models.Min('id')).delete()

seen_slugs = {}

for category in Category.objects.order_by('id'):
base_slug = category.slug
counter = 1
while category.slug in seen_slugs:
category.slug = f"{base_slug}-{counter}"
counter += 1
seen_slugs[category.slug] = True
category.save()

class Migration(migrations.Migration):

dependencies = [
Expand Down
9 changes: 7 additions & 2 deletions server/apps/research/models/category.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,13 @@ class Meta:
verbose_name_plural = 'Categories'

def save(self, *args, **kwargs):
if not self.slug:
self.slug = self.generate_slug()
try:
if not self.slug:
self.slug = self.generate_slug()
if len(self.slug) > 255:
raise ValueError("Generated slug exceeds maximum length")
except ValueError as e:
raise ValueError(f"Failed to generate valid slug: {str(e)}")
super().save(*args, **kwargs)

def __str__(self):
Expand Down

0 comments on commit 6ec47b2

Please sign in to comment.