我想建立这个层次结构:
<ul id="red" class="treeview-red">
<li><span>Item 1</span>
<ul>
<li><span>Item 1.0</span>
<ul>
<li><span>Item 1.0.0</span></li>
</ul>
</li>
<li><span>Item 1.1</span></li>
</ul>
</li>
<li><span>Item 2</span>
<ul>
<li><span>Item 2.0</span>
<ul>
<li><span>Item 2.0.0</span>
<ul>
<li><span>Item 2.0.0.0</span></li>
<li><span>Item 2.0.0.1</span></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li class="open"><span>Item 3</span>
<ul>
<li class="open"><span>Item 3.0</span>
<ul>
<li><span>Item 3.0.0</span></li>
<li><span>Item 3.0.1</span>
<ul>
<li><span>Item 3.0.1.0</span></li>
<li><span>Item 3.0.1.1</span></li>
</ul>
</li>
<li><span>Item 3.0.2</span>
<ul>
<li><span>Item 3.0.2.0</span></li>
<li><span>Item 3.0.2.1</span></li>
<li><span>Item 3.0.2.2</span></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
使用此模型:
class Category(models.Model):
parent=models.ForeignKey('self',null=True,blank=True)
name=models.CharField(max_length=100)
在 views.py 中,我编写了这个简单的代码来获取类别:
def getCats(request):
cats=Category.objects.all()
str=u''
str+='<li><span>Item 1</span><ul>'
for cat in cats:
str+=hiararchy(cat)
str+=u'</ul></li>'
return HttpResponse(simplejson.dumps(str),mimetype='application/json')
def hiararchy(cat):
s=''
if cat.parent is None or cat.parent==cat:
s=cat.name
else:
s=cat.name
return hiararchy(cat.parent)
return s
我不知道如何使用这种格式获取类别,坦率地说,我不太擅长递归函数。