Django: Loop / iterate nested list with multiple sublevels

Here are my snippets:

    class Item(models.Model):
        name = models.CharField('Name', max_length=50, unique=True)
        toplevel = models.BooleanField('Top level item', default=False)
        order = models.IntegerField('Order number', blank=True, null=True) #only if top level is true, determines the top level order

    class Hierarchy(models.Model):
        mainitem = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='mainitem')
        subitem = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='subitem')
        order = models.IntegerField('Order number', default=0) #determines the order of the subitems under the mainitem

    def items_view(request, *args, **kwargs):

        items = Item.objects.all()
        toplevelitems = Item.objects.filter(toplevel=True)
        sublevelitems = Item.objects.filter(toplevel=False)

        context = {
        return render(request, "itemlist.html", context)


    {% if items %}
            <ul class="list-group list-group-flush">
                {% for toplevelitem in toplevelitems %}
                <li class="list-group-item">{{ toplevelitem.order }} {{ }}</li>
                {% for sublevelitem in sublevelitems %}
                <ul class="list-group list-group-flush">
                    <li class="list-group-item">{{ }}</li>
                {% endfor %}
                {% endfor %} 
    {% else %}
        <p>No created items</p>
    {% endif %}

So what I am trying to built with these is a hierarchy of items that will be itereted for the client in a nested list. What I cannot figure out is how to loop through all the levels of the hierarchy and place them under the right upper level. Here is what I am going for:

    Item 1 (top level item)
        Item 1.1 (sub level item)
            Item 1.1.1 (sub sub level item)
                Item (sub sub level item)
                    item 1.....n (n sub level item) 
        Item 1.2 (sub level item)
            Item 1.2.1 (sub sub level item)
                Item (sub sub level item)
                    item 1.....n (n sub level item) 

    Item 2 (top level item)
        Item 2.1 (sub level item)
            Item 2.1.1 (sub sub level item)
                Item (sub sub level item)

    and so on...

Problem with this is the nested list can contionue up to anything and I don't know how to loop it to the last bit.

I know that the loop in html isn't doing anything like this, it only list all the subitems not considering where it belongs in the hierarchy. What would I need to change, probably in my queries and html to do something like I want?

Back to Top