Create a table in the database, with ID, Fatherid, value three fields, you can store a tree.
How to put the table data in the form of a tree, the following little brother with Python simple simulation.
Beginner python, please give us a lot of advice. In addition very grateful http://www.cnblogs.com/lzyzizi/to younger brother's guidance.
Operation Result:
A-1
B-1
C-1
D-1
E-1
E-2
C-2
B-2
C-3
C-4
Source:
1 #!user/bin/python
2
3 classNotemodel:
4 def__init__(Self,id,value,fatherid):
5 Self . Id=Id
6 Self.value=value
7 Self.fatherid=Fatherid
8 Self.children= []
9
Ten defAddChild (self,*Child ):
One Self.children+=Child
A
- defPrinttree (Self,layer):
- Print''*Layer+Self.value
the Map (Lambdachild:child.printTree (Layer+1), Self.children)
-
- defMain ():
-
+ #data table simulation, database has Id, value, Fatherid three fields, t1-t10 represents 10 rows of data
- T1=Notemodel (1,'A-1', 0)
+ T2=Notemodel (2,'B-1',1)
A T3=Notemodel (3,'B-2',1)
at T4=Notemodel (4,'C-1',2)
- T5=Notemodel (5,'C-2',2)
- T6=Notemodel (6,'C-3',3)
- T7=Notemodel (7,'C-4',3)
- T8=Notemodel (8,'D-1',4)
- T9=Notemodel (9,'E-1',8)
in T10=Notemodel (Ten,'E-2',8)
-
to #querying the database and generating the list
+ List=[T1,t2,t3,t4,t5,t6,t7,t8,t9,t10]
-
the #looping lists, binding parent-child relationships, forming a tree
* forIinchRange (0, Len (list)):
$ forJinchRange (0, Len (list)):
Panax Notoginseng ifList[j].fatherid==List[i]. Id:
- List[i].addchild (List[j])
the
+ #Print Tree
A t1.printtree (0)
the
+ if__name__=="__main__":
- Main ()
Python simple simulation: storing a tree in a data table