Skip to content

Commit f7d6b38

Browse files
committed
Added convenient get_closest_ancestor_of_type() and get_ancestors_of_type() methods
1 parent 96312aa commit f7d6b38

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

polymorphic_tree/models.py

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
from django.core.exceptions import ValidationError
77
from django.utils.translation import ugettext_lazy as _
88
from django.utils.six import integer_types
9-
from mptt.models import MPTTModel, MPTTModelBase, TreeForeignKey
9+
from mptt.models import MPTTModel, MPTTModelBase, TreeForeignKey, raise_if_unsaved
1010
from polymorphic.base import PolymorphicModelBase
1111
from polymorphic_tree.managers import PolymorphicMPTTModelManager
1212

@@ -88,6 +88,26 @@ class Meta:
8888
# class MPTTMeta:
8989
# order_insertion_by = 'title'
9090

91+
@raise_if_unsaved
92+
def get_closest_ancestor_of_type(self, model, include_self=False):
93+
"""
94+
Find the first parent of a specific model type.
95+
"""
96+
if include_self and isinstance(self, model):
97+
return self
98+
else:
99+
try:
100+
return self.get_ancestors_of_type(model, ascending=False)[0]
101+
except IndexError:
102+
return None
103+
104+
@raise_if_unsaved
105+
def get_ancestors_of_type(self, model, ascending=False, include_self=False):
106+
"""
107+
Find a parent of a specific type.
108+
"""
109+
return self.get_ancestors(ascending=ascending, include_self=include_self).instance_of(model)
110+
91111

92112
if django.VERSION < (1,7):
93113
# South integration

0 commit comments

Comments
 (0)