From 3b4df524d3fa7795f9bb8f20919cabee163d7acc Mon Sep 17 00:00:00 2001 From: Raphael Odini Date: Fri, 29 Mar 2024 09:54:46 +0100 Subject: [PATCH] Utils: new get_object_by_id_or_none --- lemarche/utils/models.py | 10 ++++++++++ lemarche/utils/tests_models.py | 24 ++++++++++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 lemarche/utils/models.py create mode 100644 lemarche/utils/tests_models.py diff --git a/lemarche/utils/models.py b/lemarche/utils/models.py new file mode 100644 index 000000000..f4d31833b --- /dev/null +++ b/lemarche/utils/models.py @@ -0,0 +1,10 @@ +def get_object_by_id_or_none(classmodel, id: int | str | None): + """ + https://stackoverflow.com/a/20674112/4293684 + """ + if id: + try: + return classmodel.objects.get(id=int(id)) + except classmodel.DoesNotExist: + pass + return None diff --git a/lemarche/utils/tests_models.py b/lemarche/utils/tests_models.py new file mode 100644 index 000000000..e1bc9aa00 --- /dev/null +++ b/lemarche/utils/tests_models.py @@ -0,0 +1,24 @@ +from django.test import TestCase + +from lemarche.siaes.models import Siae +from lemarche.utils.models import get_object_by_id_or_none + + +class ModelsTest(TestCase): + @classmethod + def setUpTestData(cls): + cls.siae = Siae.objects.create() + + def test_get_object_by_id_or_none(self): + # None + result = get_object_by_id_or_none(Siae, None) + self.assertIsNone(result) + # wrong id + result = get_object_by_id_or_none(Siae, self.siae.id + 1) + self.assertIsNone(result) + # id exists (but string) + result = get_object_by_id_or_none(Siae, str(self.siae.id)) + self.assertEqual(result, self.siae) + # id exists + result = get_object_by_id_or_none(Siae, self.siae.id) + self.assertEqual(result, self.siae)