How do I organize a list of items by category in Django?

I have a Category model and a Project model that contains a ForeignKey for the Category. Therefore, each project can belong to only one category.

I want to create a list that looks like this:

Category 1
Project 1
Project 2

Category 2
Project 3
Project 4

and etc.

I think the following psuedocode will work:

<ul class="category-list">
{% for c in category %}
    <li>{{ c.title }}</li>
    <ul class="project-list">
        {% for p in project WHERE CATEGORY = C %}
            <li>{{ p.title }}</li>
        {% endfor %}
    </ul>
{% endfor %}
</ul>

In the part that I came across, there is the "WHERE CATEGORY = C" part. How to express this in Django template code?

+3
source share
2 answers
{% for p in c.project_set.all %}

Django .

+3

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


All Articles