Django中物化路径树结构的简单轻量级实现。
django-materialized-paths的Python项目详细描述
django物化路径
Django中物化路径树结构的简单轻量级实现。
安装
要安装,请运行:
pip install django-materialized-paths
配置
将以下内容添加到项目的已安装应用程序中:
INSTALLED_APPS=(...'django-materialized-paths',)
用法
要使用,请将BaseNode
扩展到模型中:
fromdjango-materialized-pathsimportBaseNodeclassFolderExample(BaseNode):"""My folder class"""name=models.CharField(max_length=48)
该模型重写django的django.db.models.Model
save()方法,以自动管理对继承的更改:
from.modelsimportFolderExample# concrete class from aboveroot=FolderExample.objects.create(name="root")child=FolderExample.objects.create(name="child",parent=root)grandchild=FolderExample.objects.create(name="child",parent=child)
例如,要将grandchild
转换为根:
grandchild.parent=Nonegrandchild.save()
使用-属性和继承
BaseNode.depth# Root is 0BaseNode.parentBaseNode.children# Only returns direct descendantsBaseNode.save()# Set the parent field to automatically manage hierarchyBaseNode.delete()# NOTE: The BaseNode.parent field is set to cascade, so deleting a parent will delete all children
用法-方法
注意,这些方法通常返回queryset
# AccessorsBaseNode.get_root()BaseNode.get_ancestor(depth=int)BaseNode.get_ancestors()BaseNode.get_descendants()BaseNode.get_siblings()# ConvenienceBaseNode.has_children()BaseNode.is_child_of(parent_id=int)# ID-based accessors - computed directly from path without accessing dbBaseNode.get_ancestors_ids()BaseNode.get_descendants_ids()
作者
- cameron mcnierney-original author-https://github.com/cmcnierney
许可证
这个项目是在麻省理工学院的许可下授权的-详细信息请参见LICENSE.md文件