diff --git a/src/openklant/components/klanten/api/tests/test_klant.py b/src/openklant/components/klanten/api/tests/test_klant.py index 2565c4a4..7a5a0ed7 100644 --- a/src/openklant/components/klanten/api/tests/test_klant.py +++ b/src/openklant/components/klanten/api/tests/test_klant.py @@ -377,7 +377,16 @@ def test_create_klant_website_url_optional(self): self.assertEqual(klant.bronorganisatie, "950428139") self.assertEqual(klant.website_url, "") - self.assertTrue(klant.klantnummer != 0) + self.assertEqual(klant.klantnummer, "1") + + with requests_mock.Mocker() as m: + m.get(SUBJECT, json={}) + response = self.client.post(list_url, data) + + self.assertEqual(response.status_code, status.HTTP_201_CREATED) + + klant = Klant.objects.get(klantnummer__gt=1) + self.assertEqual(klant.klantnummer, "2") def test_create_klant_website_url_duplicate_klantnummer(self): list_url = reverse(Klant) diff --git a/src/openklant/components/klanten/models/klanten.py b/src/openklant/components/klanten/models/klanten.py index 8806dddd..0c16ed9d 100644 --- a/src/openklant/components/klanten/models/klanten.py +++ b/src/openklant/components/klanten/models/klanten.py @@ -15,8 +15,10 @@ class KlantManager(models.Manager): def get_next_klantnummer(self): - id_max = Klant.objects.all().aggregate(Max("klantnummer"))["id__max"] - return id_max + 1 if id_max else 1 + id_max = Klant.objects.all().aggregate(models.Max("klantnummer"))[ + "klantnummer__max" + ] + return int(id_max) + 1 if id_max else 1 class Klant(APIMixin, models.Model): @@ -102,6 +104,8 @@ class Meta: verbose_name_plural = "klanten" def save(self, *args, **kwargs): + if not self.klantnummer: + self.klantnummer = Klant.objects.get_next_klantnummer() if not self.pk: if Klant.objects.filter(klantnummer=self.klantnummer): raise Conflict("Klantnummer bestaat al")