Django,类别和子类别
-
07-07-2019 - |
题
我的工作类别和子类别为 数据模型, ,这部分一切都很好,但我需要在菜单导航中使用我的类别和子类别,我尝试使用这个 jQuery菜单 ,并且我用子类别渲染我的菜单,但我迷失了以以下方式渲染子类别:
<ul>
<li>
<a href="#">Category</a>
<!--subcategories-->
<span>Subcategory 1 </span>
<span>Subcategory 2 </span>
...
</li>
....
....
</ul>
我的问题:在数据模型中:对于“自我”,我不知道在这种情况下如何创建子类别(父级就是字段本身)。
class Category(models.Model):
name = models.CharField(core=True, maxlength=200)
slug = models.SlugField(prepopulate_from=('name',))
parent = models.ForeignKey('self', blank=True, null=True, related_name='child')
description = models.TextField(blank=True,help_text="Optional")
谢谢
解决方案
使用类似的方法获取所有顶级类别
top_level_cats = Category.objects.filter(parent__isnull=True)
然后:
for tlc in top_level_cats:
#do the HTML for the top-level category
for clc in tlc.child.all():
#do the HTML for the children of clc
如果您有多个级别类别,则需要在某处进行递归调用,但这给出了基本要点。
不隶属于 StackOverflow