Lepus
Lepus

Reputation: 587

Ordering django field values in a list

I've the following model:

class Blog():
     year = models.PositiveSmallIntegerField()
     title = models.Charfield(max_length=40)

Now in my template I currently display this field values like so:

{% for blog in blogs %}

    {% ifchanged %}
        <li>{{blog.year}}</li>
    {% endifchanged %}

    <li><a href="#">{{ blog.title }}</a></li>

{% endfor %}

Which gives me the following html output:

<ul>
    <li>2016</li>
    <li><a href="#">title 1</a></li>
    <li><a href="#">title 2</a></li>
    <li>2012</li>
    <li><a href="#">title 3</a></li>
</ul>

But what I'd like to get would be the following:

<ul>

    <li>2016
        <ul>
            <li><a href="#">title 1</a></li>
            <li><a href="#">title 2</a></li>
        </ul>
    </li>

    <li>2012
        <ul>
            <li><a href="#">title 3</a></li>
        </ul>
    </li>

</ul>

Is there a way to do this in django templates?

Upvotes: 0

Views: 27

Answers (1)

Sayse
Sayse

Reputation: 43330

You can use regroup

{% regroup blogs by year as blog_list %}

<ul>
{% for blog in blog_list %}
    <li>{{ blog.grouper }}
    <ul>
        {% for item in blog.list %}
          <li><a href="#">{{ item.title }}</a></li>
        {% endfor %}
    </ul>
    </li>
{% endfor %}
</ul>

Upvotes: 3

Related Questions