Reputation: 373
Suppose I have a list of countries and I want to display them grouping by continents. My models.py looks like this
class Countries(models.Model):
name = models.CharField(max_length=200)
continent = models.CharField(max_length=200)
And, my views.py looks like this:
class ListCountriesView(ListView):
model = Countries
template_name = 'country_list.html'
My html displays the folowing list
Asia
Japan
Asia
S.Korean
Asia
China
Asia
India
Europe
Germany
Europe
France
Europe
Belgium
Africa
Ghana
My country_list.html looks like this:
<html>
<table>
<tr><th>Country</th></tr>
{% for country in object_list%}
<td>kpi.continent</td>
<tr><td>country.name</td></tr>
</table>
</html>
I want to display the continent's name once and followed by the respective cooutries. I cannot figure out how to group the list by continent.Is there any fllter function that I can use in django template ?
Upvotes: 1
Views: 2858
Reputation: 27861
Yep. There certainly is:
{% regroup object_list by continent as continents_list %}
<ul>
{% for continent in continents_list %}
<li>{{ continent.grouper }}
<ul>
{% for item in continent.list %}
<li>{{ item.name }}</li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
Upvotes: 5
Reputation: 1
it helped solve my problem as a Django newbie. As an aside I was using a Django standard List View to display event winners by event. The regroup helped me to group by events as above, but my order for the podium finishers was being displayed randomly. This was solved by ordering the List View as per the code snippet.
class WinnerListView(ListView):
model = Winner
template_name = "scores/winners.html"
context_object_name = "winners"
ordering = ["score_id__sevent", "-prize"]
paginate_by = 16
Upvotes: 0