How to create nested groups in Django?

I have the following situation in this system: Each product category has many subcategories, and each subcategory has many products under it. I am trying to make a searh product that returns a list, and in my template I show an overview of the results, for example:

Cellphones
    Dumbphones (2 results)
    Smartphones (3 results)
Monitors
    CRT (1 result)
    LCD (3 results)

I am my template. I have only a list of products. I have tried many combinations of nested groups without success. Any ideas?

+3
source share
1 answer

You can try something like this:

<div>    
...
{% regroup results|dictsort:"subcategory.category" by subcategory.category as categories %}
<ul>
    {% for category in categories %}
    <li>{{ category.grouper }}
        {% regroup category.list|dictsort:"subcategory" by subcategory as subcategories %}
        <ul>
            {% for subcategory in subcategories %}
                <li>{{ subcategory.grouper }}
                    <!--The same way you can render a subcategory.list which is the prosucts list-->
                </li>
            {% endfor %}
        </ul>
    </li>
    {% endfor %}
</ul>
acceptance_report.company as companies %}
...
</div>
+1
source

Source: https://habr.com/ru/post/1785091/


All Articles