0👍
✅
finally I came up with this solution:
def getCats(request):
cats=Category.objects.filter(parent=None)
s=u'<ul id="red" class="treeview-red">'
for cat in cats:
s += hiararchy(cat,True)
s+=u'</ul>'
return HttpResponse(simplejson.dumps(s),mimetype='application/json')
def hiararchy(cat,flag):
if cat.parent and flag:
return hiararchy(cat.parent,True)
else:
if cat.children.count()>0:
s=u'<li><a href="#" id="'+str(cat.pk)+'" class="cat">%s</a>'%(cat.name)
for child in cat.children.all():
s+=u'<ul>%s</li></ul></li>'%(hiararchy(child,False))
return s
else:
return u'<li><a href="#" id="'+str(cat.pk)+'" class="cat">%s</a></li>'%(cat.name)
pay attention :
1)when a category don’e have parent it means it’s the root node in tree
2)numbering in my example didn’t implement in my code,I needed to replace the name of categories in place of those numbers
1👍
perhaps you’ll find this post useful: I asked a similar question a while back with recursion that looks a bit like yours
Python Recursion through objects and child objects, Print child depth numbers
- [Answer]-Passing a list of URLS from one page to another
- [Answer]-Django – what is the most commonly accepted way of including a form within another template?
Source:stackexchange.com