递归函数没有按预期递增 - python / django

时间:2014-02-07 22:59:18

标签: python django recursion tree nodes

我正在使用Django模型创建一个树应用程序。基本上,用户输入不同节点的名称,如果节点连接到另一个节点,则递归函数将1添加到父节点的“nodes”属性。只要我添加将父项总数增加到> 2的节点,它就会停止递增并保持为2。这是代码:

class Node(models.Model):
    name = models.CharField(max_length=200)
    parent = models.ForeignKey('self', null=True)
    nodes = models.IntegerField(default=0)

    def __unicode__(self):
        return self.name

用户输入文字。例如,假设用户输入以下内容:

"animal(dog)"
"dog(golden retriever)"  # animal nodes should be 2 (and it is)
"golden retriever(old yeller)" # animal nodes should now be 3 but it remains 2

这应该生成一个这种结构的树:

     animal   (3 nodes)
   /         
dog      (2 nodes)      
  |
golden retriever   (1 node)
  | 
 old yeller  (0 nodes)

不知何故,node_ancestors方法最初只能正常运行。关于我的观点出了什么问题的任何想法?

def node_ancestors(node):  

    ancestor = node.parent 

    if ancestor != None: 

        ancestor.nodes += 1
        print ancestor, " just added a node.   it now has %d nodes. " % (ancestor.nodes)
        node.save()
        node_ancestors(ancestor)

def index(request):
    nodes = Node.objects.all()
    node_names = [a.name for a in nodes]

if request.method == 'POST':  
    node_string = request.POST.get('get_node')
    print node_string
    index = node_string.find('(')
    parent = node_string[0:index]
    child = node_string[index+1:len(node_string)-1]

    if parent not in moment_names and child not in node_names:
        parent = Node(name=parent, nodes=1)
        parent.save()
        child = Node(name=child, parent=parent)
        child.save()
        print "parent is", parent
        print "child is", child
        print "parent nodes: ", parent.nodes
        print "child nodes: ", child.nodes

    elif parent in node_names and child not in node_names:
        parent_model = nodes.get(name=parent)

        node_ancestors(parent_model)  # adds 1 to all nodes superior to parent node

        child = Node(name=child, parent=parent_model)

        child.save()


    elif parent not in node_names and child in node_names:
        parent = Node(name=parent, nodes=child_model.nodes+1)
        parent.save()
        print "parent is", parent

return render(request, 'nodes_app/index.html')

1 个答案:

答案 0 :(得分:0)

对于这类事情,你可以使用Django MPTT(http://django-mptt.github.io/django-mptt/),它可以用来构建树模型,并有一个lot of built-in methods来获取/显示祖先/孩子。

以下是根据您提供的代码构建的简单示例:

from django.db import models
from mptt.models import MPTTModel, TreeForeignKey


class Species(MPTTModel):
    name = models.CharField(max_length=50, unique=True)
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children')

    class MPTTMeta:
        order_insertion_by = ['name']

dog = Species()
dog.name = "Dog"
dog.save()

golden = Species()
golden.name = "Golden Retriever"
golden.parent = dog
golden.save()

old = Species()
old.name = "Old Yeller"
old.parent = golden
old.save()


print(dog.level)    # 0
print(golden.level) # 1
print(old.level)    # 2

ancestors = old.get_ancestors(include_self=True)

for each species in ancestors:
    print(species.name)

# Dog
# Golden Retriever
# Old Yeller