Commits

Lars Yencken committed 17dff34

Adds an example of usage

Comments (0)

Files changed (1)

 
 For comparison, see the [[http://code.google.com/p/django-mptt/|django-mptt]] project which provides similar functionality, and is probably better documented.
 
+=== Example ===
+
+Firstly, define your model by subclassing the {{{HierarchicalModel}}} class.
+
+{{{
+#!python
+
+from django.db import models
+from hierarchy.models import HierarchicalModel
+
+class FoodType(HierarchicalModel):
+    name = models.CharField(max_length=100)
+}}}
+
+Two extra hidden integer fields have been created for you, {{{left_visit}}} and {{{right_visit}}}, which are needed for the nested set abstraction to work.
+
+There are several ways you can go from here, depending on your application.
+
+==== Option A: store an entire tree at once ====
+
+This is the faster way to construct a tree. Firstly, build your tree.
+
+{{{
+#!pycon
+>>> from hierarchy.tree import TreeNode
+>>> food = TreeNode('food')
+>>> fruit = TreeNode('fruit')
+>>> food.add_child(fruit)
+>>> for name in ('apple', 'orange', 'banana'):
+>>>     fruit.add_child(TreeNode(name))
+>>> food.layout() # pretty-print the tree
+food
+└─ fruit
+   ├─ orange
+   ├─ apple
+   └─ banana
+}}}
+
+Now that you've built the tree, you can store it to your model as follows:
+
+{{{
+#!pycon
+>>> food.store(FoodType, label_field='name')
+}}}
+
+You just provide your model (in this case {{{FoodType}}}), and tell it which field to map node labels to. Note that storing the tree this way will clear any existing nodes from the database, effectively overwriting them. 
+
+==== Option B: add things incrementally ====
+
+If you add things incrementally, each extra insert takes additional time since it also needs to perform an SQL {{{UPDATE}}} on the entire tree. Still, this way is supported for situations when you don't know the tree in advance.
+
+//To be completed...//
 
 === Download ===