Django如何通过自参考模型制作ul li hichychy [英] Django how to make ul li hierachy from a self reference model

查看:85
本文介绍了Django如何通过自参考模型制作ul li hichychy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的模型

class Unit(models.ModelForm):
    Name = models.CharField(max_length =  100)
    Parent = models.ForeignKey('self' , on_delete=models.CASCADE , related_name = 'SubUnits')

我想在模板中显示带有ul and li的层次树. 首先,在views.py中,我传递了没有父级的所有单元,这些父级被视为根对象,然后使用自定义的filter tag,我想生成层次结构ul li tree

i want to show hierarchy tree with ul and li in the template. first of all in the views.py i passed all Units with no parent which considered as Root Objects and then with a custom filter tag i want to generate hierarchy ul li tree

object1 ----|object 1.1 
            |object 1.2------| object 1.2.1
            |object 1.3 
objecte 2

object 3 ---| object 3.1
            | object 3.2---| object 3.2.1

在我的自定义标签中,我寻找一个可以为根对象生成无限父级和子级ul li的函数.

in my custom tag i looks for a function that can generate infinite parent and child ul li for my root object.

推荐答案

最后我找到了我的算法

models.py

models.py

class Hierarchy(models.Model):
    Name = models.CharField(max_length=255)
    Parent = models.ForeignKey('self' , on_delete=models.CASCADE , related_name='SubHierarchy' , null=True , blank=True)
    def __str__(self):
        return self.Name

我的views.py:

my views.py:

#i pass root objects 
hierarchy = Hierarchy.objects.filter(Parent = None)
return render(request , 'index.html' , {
   'hierarchy' : hierarchy
 })

模板:

 {% for unit in hierarchy %}
   {{unit|hierarchy|safe}}
 {% endfor %}

和我的过滤器:

def assitant(obj):
    string = ''
    childs = obj.SubHierarchy.all()
    if childs.count() == 0:
        string = '<li>{}</li>'.format(obj)
    else:
        string += hierarchy(obj)

    return string


@register.filter
def hierarchy(unit):
    childs = unit.SubHierarchy.all()
    if childs.count() == 0:
        string = '<li>{}</li>'.format(unit)
    else:
        string = '<li>{}<ul>'.format(unit)
        for child in childs:
            string += assitant(child)
        string += '</ul></li>'
    return string

这篇关于Django如何通过自参考模型制作ul li hichychy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆