diff --git a/lemarche/siaes/models.py b/lemarche/siaes/models.py index 05ff2ef4d..e625b653c 100644 --- a/lemarche/siaes/models.py +++ b/lemarche/siaes/models.py @@ -1262,7 +1262,17 @@ def clean(self): Does not use a unique constraint on model because it allows blank values and checks two fields simultaneously. """ super().clean() + + # Check only if brand is set and different from the original brand + # (to avoid validation error on update without brand change) + check_brand_uniqueness = False if self.brand: + check_brand_uniqueness = True + if self.pk: + original_brand = Siae.objects.get(pk=self.pk).brand + check_brand_uniqueness = original_brand != self.brand + + if check_brand_uniqueness: # Check if brand is used as name by another Siae name_exists = Siae.objects.exclude(id=self.id).filter(Q(name=self.brand) | Q(brand=self.brand)).exists() if name_exists: diff --git a/lemarche/siaes/tests/test_models.py b/lemarche/siaes/tests/test_models.py index fb2fe0eaa..ea6b5fc94 100644 --- a/lemarche/siaes/tests/test_models.py +++ b/lemarche/siaes/tests/test_models.py @@ -1,3 +1,4 @@ +from django.core.exceptions import ValidationError from django.test import TestCase from django.utils import timezone @@ -418,6 +419,45 @@ def test_set_super_badge(self): self.assertTrue(siae_super_badge_2.super_badge) self.assertEqual(siae_super_badge_2.super_badge_last_updated, siae_super_badge_last_updated_current_value) + def test_brand_uniqueness(self): + SiaeFactory(name="Name 1", brand="Brand 1") + SiaeFactory(brand="Brand 2") + siae_3 = SiaeFactory(brand="Brand 1") + self.assertEqual(Siae.objects.filter(brand="Brand 1").count(), 2) + + # can update something else than brand + siae_3.contact_first_name = "Contact 1" + siae_3.clean() + siae_3.save() + + self.assertEqual(Siae.objects.filter(brand="Brand 1").count(), 2) + siae_3.refresh_from_db() + self.assertEqual(siae_3.contact_first_name, "Contact 1") + + # can't update brand to an existing brand + siae_3.brand = "Brand 2" + with self.assertRaises(ValidationError): + siae_3.clean() + siae_3.save() + self.assertEqual(Siae.objects.filter(brand="Brand 1").count(), 2) + + # can't update brand to an existing name + siae_3.brand = "Name 1" + with self.assertRaises(ValidationError): + siae_3.clean() + siae_3.save() + + siae_3.refresh_from_db() + self.assertEqual(siae_3.brand, "Brand 1") + + # can update brand to a non existing brand + siae_3.brand = "Brand 3" + siae_3.name = "Name 3" + siae_3.clean() + siae_3.save() + siae_3.refresh_from_db() + self.assertEqual(siae_3.brand, "Brand 3") + class SiaeModelQuerysetTest(TestCase): @classmethod