Django how to make ul li hierachy from a self reference model

别等时光非礼了梦想. 提交于 2019-12-11 16:55:57

问题


i have a model like this

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

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

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


回答1:


finally i find my algorithm

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

my views.py:

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

template :

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

and my filter :

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


来源:https://stackoverflow.com/questions/44690708/django-how-to-make-ul-li-hierachy-from-a-self-reference-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!