我尝试创建下拉菜单。菜单包括可以是父母或孩子的类别。当您针对父元素时,下拉菜单会起作用,并且您会看到该父元素的所有子元素。为此,我使用mptt。
我的模型。py:
类别Category(MPTTModel):
name = models.CharField(max_length=50, unique=True)
parent = TreeForeignKey('self', null=True, blank=True, related_name='children', on_delete=models.CASCADE, db_index=True)
slug = models.SlugField()
class MPTTMeta:
order_insertion_by = ['name']
class Meta:
unique_together = (('parent', 'slug',))
verbose_name_plural = 'categories'
def get_slug_list(self):
try:
ancestors = self.get_ancestors(include_self=True)
except:
ancestors = []
else:
ancestors = [ i.slug for i in ancestors]
slugs = []
for i in range(len(ancestors)):
slugs.append('/'.join(ancestors[:i+1]))
return slugs
def __str__(self):
return self.name
我的查询:
category = Category.objects.all()
我的模板:
<ul class="header__nav">
{% recursetree category %}
<li class="has-children">
{{ node.name }}
{% if not node.is_leaf_node %}
<ul class="sub-menu ">
{{ children }}
</ul>
{% endif %}
</li>
{% endrecursetree %}
</ul>
显示很好。但是我无法将子级作为对象并获得它的名称或名称,因为 children:此变量保存节点的子级呈现的HTML。 我该怎么做才能让孩子成为对象?