from django.db.models import get_model

Category = get_model('catalogue', 'category')


def create_from_sequence(bits):
    """
    Create categories from an iterable
    """
    if len(bits) == 1:
        # Get or create root node
        try:
            root = Category.objects.get(depth=1, name=bits[0])
        except Category.DoesNotExist:
            root = Category.add_root(name=bits[0])
        return [root]
    else:
        parents = create_from_sequence(bits[:-1])
        try:
            child = parents[-1].get_children().get(name=bits[-1])
        except Category.DoesNotExist:
            child = parents[-1].add_child(name=bits[-1])
        parents.append(child)
        return parents


def create_from_breadcrumbs(breadcrumb_str, separator='>'):
    """
    Create categories from a breadcrumb string
    """
    category_names = [x.strip() for x in breadcrumb_str.split(separator)]
    categories = create_from_sequence(category_names)
    return categories[-1]

@@ -225,36 +225,120 @@
 ot node%0A        
-try:
+name = bits%5B0%5D%0A        try:%0A            # Category names should be unique at the depth=1
 %0A            roo
@@ -372,31 +372,28 @@
 pth=1, name=
-bits%5B0%5D
+name
 )%0A        ex
@@ -462,23 +462,205 @@
 ot(name=
-bits%5B0%5D
+name)%0A        except Category.MultipleObjectsReturned:%0A            raise ValueError((%0A                %22There are more than one categories with name %22%0A                %22%25s at depth=1%22) %25 name
 )%0A      
@@ -731,24 +731,69 @@
 (bits%5B:-1%5D)%0A
+        parent, name = parents%5B-1%5D, bits%5B-1%5D%0A
         try:
@@ -819,21 +819,16 @@
 = parent
-s%5B-1%5D
 .get_chi
@@ -840,32 +840,28 @@
 ().get(name=
-bits%5B-1%5D
+name
 )%0A        ex
@@ -914,21 +914,16 @@
 = parent
-s%5B-1%5D
 .add_chi
@@ -930,24 +930,229 @@
 ld(name=
-bits%5B-1%5D
+name)%0A        except Category.MultipleObjectsReturned:%0A            raise ValueError((%0A                %22There are more than one categories with name %22%0A                %22%25s which are children of %25s%22) %25 (name, parent)
 )%0A      

Rework category creation from breadcrumbs