From 3908a5e118d2fc26a34d623a6a1ab4b2066a0a1f Mon Sep 17 00:00:00 2001 From: Jean-Baptiste <bleme@pm.me> Date: Wed, 20 Feb 2019 11:53:37 +0100 Subject: [PATCH] update: add resolve functions on Model --- djangoldp/models.py | 39 ++++++++++++++++++++++++------ djangoldp/tests/tests_ldp_model.py | 8 ++++++ 2 files changed, 40 insertions(+), 7 deletions(-) diff --git a/djangoldp/models.py b/djangoldp/models.py index 00c63943..f63ffd4b 100644 --- a/djangoldp/models.py +++ b/djangoldp/models.py @@ -21,7 +21,7 @@ class Model(models.Model): slug_field = '/{}'.format(get_resolver().reverse_dict[view_name][0][0][1][0]) if slug_field.startswith('/'): slug_field = slug_field[1:] - return "{}{}".format(Model.container_id(instance), getattr(instance, slug_field)) + return "{}{}".format(cls.container_id(instance), getattr(instance, slug_field)) @classmethod def container_id(cls, instance): @@ -29,19 +29,44 @@ class Model(models.Model): path = instance.container_path else: view_name = '{}-list'.format(instance._meta.object_name.lower()) - path = '/{}'.format(get_resolver().reverse_dict[view_name][0][0][0]) + path = get_resolver().reverse(view_name) - if not path.startswith("/"): - path = "/{}".format(path) - - if not path.endswith("/"): - path = "{}/".format(path) + path = cls.__clean_path(path) return path class Meta: abstract = True + @classmethod + def resolve_id(cls, id): + id = cls.__clean_path(id) + view, args, kwargs = get_resolver().resolve(id) + return view.initkwargs['model'].objects.get(**kwargs) + + @classmethod + def resolve_container(cls, path): + path = cls.__clean_path(path) + view, args, kwargs = get_resolver().resolve(path) + return view.initkwargs['model'] + + @classmethod + def resolve(cls, path): + container = cls.resolve_container(path) + try: + resolve_id = cls.resolve_id(path) + except: + resolve_id = None + return container, resolve_id + + @classmethod + def __clean_path(cls, path): + if not path.startswith("/"): + path = "/{}".format(path) + if not path.endswith("/"): + path = "{}/".format(path) + return path + class LDPSource(models.Model): container = models.URLField() diff --git a/djangoldp/tests/tests_ldp_model.py b/djangoldp/tests/tests_ldp_model.py index 8a17c88f..56bbe552 100644 --- a/djangoldp/tests/tests_ldp_model.py +++ b/djangoldp/tests/tests_ldp_model.py @@ -20,6 +20,14 @@ class LDPModelTest(TestCase): self.assertEquals("/ldp-dummys/", Model.container_id(dummy)) self.assertEquals("/ldp-dummys/{}".format(dummy.pk), Model.resource_id(dummy)) + def test_from_resolve_id(self): + saved_instance = Dummy.objects.create(some="text") + result = Model.resolve_id("/dummys/{}".format(saved_instance.pk)) + self.assertEquals(saved_instance, result) + + def test_resolve_container(self): + result = Model.resolve_container("/dummys/") + self.assertEquals(Dummy, result) @unittest.skip("futur feature: avoid urls.py on apps") def test_auto_url(self): -- GitLab