From 9ac5877d293d4e8c6f94e98f3962f7035e94e9bc Mon Sep 17 00:00:00 2001 From: smacker Date: Wed, 26 Oct 2011 12:01:37 +0600 Subject: [PATCH 1/2] add get_subclass method --- .gitignore | 1 + model_utils/managers.py | 3 +++ 2 files changed, 4 insertions(+) diff --git a/.gitignore b/.gitignore index 68cead8..4bb1a0f 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ HGREV .coverage .tox/ Django-*.egg +*.pyc \ No newline at end of file diff --git a/model_utils/managers.py b/model_utils/managers.py index 8542966..02ab29b 100644 --- a/model_utils/managers.py +++ b/model_utils/managers.py @@ -43,6 +43,9 @@ class InheritanceManager(models.Manager): def select_subclasses(self, *subclasses): return self.get_query_set().select_subclasses(*subclasses) + def get_subclass(self, *args, **kwargs): + return self.get_query_set().select_subclasses().get(*args, **kwargs) + class InheritanceCastMixin(object): def cast(self): From b06ba20fe904f33323c12b561df938db7dec65d0 Mon Sep 17 00:00:00 2001 From: smacker Date: Wed, 26 Oct 2011 23:06:55 +0600 Subject: [PATCH 2/2] test and docs for get_subclass --- README.rst | 5 +++++ model_utils/tests/tests.py | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/README.rst b/README.rst index e2b32af..3e7591d 100644 --- a/README.rst +++ b/README.rst @@ -263,6 +263,11 @@ be returned as their actual type, you can pass subclass names to nearby_places = Place.objects.select_subclasses("restaurant") # restaurants will be Restaurant instances, bars will still be Place instances +Also it provides syntax sugar for `get()` method:: + + place = Place.objects.get_subclass(id=some_id) + # "place" will automatically be an instance of Place, Restaurant, or Bar + If you don't explicitly call ``select_subclasses()``, an ``InheritanceManager`` behaves identically to a normal ``Manager``; so it's safe to use as your default manager for the model. diff --git a/model_utils/tests/tests.py b/model_utils/tests/tests.py index 816ccbe..544a5f4 100644 --- a/model_utils/tests/tests.py +++ b/model_utils/tests/tests.py @@ -353,6 +353,11 @@ if django.VERSION >= (1, 2): set([self.child1, InheritanceManagerTestParent(pk=self.child2.pk)])) + def test_get_subclass(self): + self.assertEquals( + self.get_manager().get_subclass(pk=self.child1.pk), + self.child1) + class InheritanceManagerRelatedTests(InheritanceManagerTests): def setUp(self):