From 2269ed579a99410b83fe3a332963250a1ce5240e Mon Sep 17 00:00:00 2001 From: Nina Menezes Date: Thu, 2 Jan 2025 08:56:41 +0000 Subject: [PATCH] fix the slugify method to ensure unique --- consultation_analyser/consultations/models.py | 19 +++++++++++++------ tests/unit/models/test_slug.py | 4 ++-- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/consultation_analyser/consultations/models.py b/consultation_analyser/consultations/models.py index 1a4b5d23..f81f41b8 100644 --- a/consultation_analyser/consultations/models.py +++ b/consultation_analyser/consultations/models.py @@ -1,5 +1,5 @@ +import datetime import itertools -import random import uuid from dataclasses import dataclass @@ -352,13 +352,20 @@ class SlugFromTextModel(models.Model): slug = models.SlugField(null=False, editable=False, max_length=256) def save(self, *args, **kwargs): - # Generate a slug from the text - ensure unique - cropped_length = 124 + # Generate a slug from the text - ensure unique by adding timestamp if needed + ModelClass = self.__class__ + cropped_length = 220 cropped_text = self.text[:cropped_length] generated_slug = slugify(cropped_text) - ModelClass = self.__class__ - while ModelClass.objects.filter(slug=generated_slug).exists(): - generated_slug = f"{generated_slug[:cropped_length]}-{random.randint(0, 999)}" + if self.pk: + slug_exists = ( + ModelClass.objects.filter(slug=generated_slug).exclude(pk=self.pk).exists() + ) + else: + slug_exists = ModelClass.objects.filter(slug=generated_slug).exists() + if slug_exists: + timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S%f") + generated_slug = f"{generated_slug}-{timestamp}" self.slug = generated_slug return super().save(*args, **kwargs) diff --git a/tests/unit/models/test_slug.py b/tests/unit/models/test_slug.py index 55427aeb..2a5e3740 100644 --- a/tests/unit/models/test_slug.py +++ b/tests/unit/models/test_slug.py @@ -8,7 +8,7 @@ def test_consultation_save(): consultation_title = "My First Consultation" slugified = "my-first-consultation" consultation = Consultation2Factory(text=consultation_title) - assert consultation.slug.startswith(slugified) + assert consultation.slug == slugified another_consultation = Consultation2Factory(text=consultation_title) assert another_consultation.slug != consultation.slug assert another_consultation.slug.startswith(slugified) @@ -19,7 +19,7 @@ def test_question_save(): question_text = "What are your thoughts on the proposed changes?" slugified = "what-are-your-thoughts-on-the-proposed-changes" question = Question2Factory(text=question_text) - assert question.slug.startswith(slugified) + assert question.slug == slugified another_question = Question2Factory(text=question_text) assert another_question.slug != question.slug assert another_question.slug.startswith(slugified)