1

我有一个递归关系:每个节点都有一个(可能为空)父节点。相反,每个父母都有多个孩子。我有一个 build_subtree 方法,它获取有关节点的信息并递归地构建节点并将其添加到父 FK 关系的反向集中,孩子。这似乎按预期工作,直到我保存根节点。在调用 save() 之前,root.children.count() > 0,在 save root.children.count() == 0 之后。(见下面的代码)谁能指出我正确的方向?我见过几次提到 django-mptt,我可能最终会使用它,但我真的很想先了解这一点。

class Node(models.Model):
    parent = models.ForeignKey('self', null=True, related_name='children')
    nodeVal = models.TextField()
    nodeType = models.CharField(max_length=75)
    level = models.IntegerField()

    @classmethod
    def build_subtree(cls, nodeVal, nodeType, level, children):
        root = cls(nodeVal=nodeVal, nodeType=nodeType, level=level)
        for c in children:
            root.children.add(cls.build_subtree(c['nodeVal'], c['nodeType'], c['level'], c['children']))
        return root

然后在壳内...

>>> child = {'nodeVal' : 'B', 'nodeType' : 'tag', 'level' : 1, 'children' : []}
>>> root = {'nodeVal' : 'A', 'nodeType' : 'tag', 'level' : 0, 'children' : [child]}
>>> n = Node.build_subtree(root['nodeVal'], root['nodeType'], root['level'], root['children'])
>>> n.children.count()
1
>>> n.save()
>>> n.children.count()
0
4

1 回答 1

1

问题是您的孩子没有收到对父母的参考:

>>> print n.children.all()[0].parent
None

在该build_subtree方法中,您正在创建父对象而不将其保存到数据库中,但是该add()方法将对象保存到数据库中,并且没有要设置的 FK,因为父对象还不存在!

您可能应该将类实例化替换为调用cls.objects.create或使用不同的创建顺序。

于 2012-08-02T21:47:34.570 回答