使用django模型创建、持久化和操作可靠树结构的简单方法。
django_trees的Python项目详细描述
安装
pip install django-trees
API使用
创建模型
创建模型扩展AbstractNode并添加所需字段。
fromdjango.dbimportmodelsfromdjango_trees.modelsimportAbstractNodeclassFolder(AbstractNode):name=models.CharField(max_length=10)
创建树节点
要创建树节点,除了指定父节点之外,没有什么不同于创建普通django模型。
root=Folder.objects.create(name="Root")documents=Folder.objects.create(name="Documents",parent=root)downloads=Folder.objects.create(name="Downloads",parent=root)projects=Folder.objects.create(name="Projects",parent=documents)
获取节点子体
使用get_descendants方法检索节点的所有后代(包括子代、孙子、曾孙等)。此方法将返回节点对象的平面列表。
root.get_descendants()
获取节点祖先
使用get_ancestors方法检索节点的所有祖先(包括父代、祖父母、曾祖父母等)。此方法将返回节点对象的平面列表。
projects.get_ancestors()
获取节点子节点
要检索当前节点的所有直接子节点,请使用get_children方法。此方法将返回节点对象的平面列表。
projects.get_children()
移动节点
若要将节点移动到树中的其他位置,请使用move方法将新父节点作为参数传递。
projects.move(root)
分叉节点
< >从现有树的分支创建一个单独的树,使用^ {TT7}$方法。节点对象将从上一个树中删除,它及其子对象现在将位于新树中。projects.bifurcate()
获取ascii树
要获取树结构的ascii表示,请使用get_ascii_tree方法。
projects.get_ascii_tree()