def BuildList(categories):
list = []
for category in categories:
if len(category.childrens.all()):
list.append(category)
list.append(BuildList(category.childrens.all()))
else :
list.append(category)
return list
list = BuildList(Categories.objects.filter(parent = None))
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/LwmJH2ZcRcwJ.
To post to this group, send email to django...@googlegroups.com.
To unsubscribe from this group, send email to django-users...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
I suppose that "childrens" is a custom manager, can you show us, the implementation of that manager?
class Categories(models.Model):
name = models.CharField(max_length=50)
path = models.SlugField(max_length=50)
parent = models.ForeignKey('self', null=True, blank=True, related_name='childrens')
order = models.IntegerField(default=1)
isShow = models.BooleanField(default=True)
Only for performance "if len(category.childrens.all()):" -> "if category.childrens.exist():"
But your problem, it's rare. Print the type of the firs element of the result list:
{% load menu_builder %}
{{ list|BuildMenu }}
def BuildMenu(list):
html = ''
for item in list:
print item.path
return html
You are probably getting this error because when you generate your list from categories. you are adding sub categories as list. so your list will be like following
[cat1,cat2,cat3,[subcat1,subcat2],[subcat3,subcat4]]
Lastly please check this https://github.com/django-mptt/django-mpttthis is great for categories. this is good for keeping trees in relational databases. when you query sub trees, it will do exactly one query every time.and there is a generic category app too if you need.I hope that helps.