- slugs = path.split(pathsep)
- obj = root
- remaining_slugs = list(slugs)
- remainder = None
- for slug in slugs:
- remaining_slugs.remove(slug)
- if slug: # ignore blank slugs, handles for multiple consecutive pathseps
+ segments = path.split(pathsep)
+
+ # Clean out blank segments. Handles multiple consecutive pathseps.
+ while True:
+ try:
+ segments.remove('')
+ except ValueError:
+ break
+
+ # Special-case a lack of segments. No queries necessary.
+ if not segments:
+ if root is not None:
+ return root, None
+ else:
+ raise self.model.DoesNotExist('%s matching query does not exist.' % self.model._meta.object_name)
+
+ def make_query_kwargs(segments):
+ kwargs = {}
+ prefix = ""
+ revsegs = list(segments)
+ revsegs.reverse()
+
+ for segment in revsegs:
+ kwargs["%s%s__exact" % (prefix, field)] = segment
+ prefix += "parent__"
+
+ kwargs[prefix[:-2]] = root
+ return kwargs
+
+ def find_obj(segments, depth, deepest_found):
+ try:
+ obj = self.get(**make_query_kwargs(segments[:depth]))
+ except self.model.DoesNotExist:
+ if absolute_result:
+ raise
+
+ depth = (deepest_found + depth)/2
+ if deepest_found == depth:
+ # This should happen if nothing is found with any part of the given path.
+ raise
+
+ # Try finding one with half the path since the deepest find.
+ return find_obj(segments, depth, deepest_found)
+ else:
+ # Yay! Found one! Could there be a deeper one?
+ if absolute_result:
+ return obj
+
+ deepest_found = depth
+ depth = (len(segments) + depth)/2
+
+ if deepest_found == depth:
+ return obj, pathsep.join(segments[deepest_found:]) or None
+