Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django grouping queryset by first letter?

I have a QuerySet like:

items = Item.objects.all()

Item has a 'name' field. In the template I want to show:

  • A
  • Axes
  • Alcohol
  • B
  • Bazookas
  • C
  • Coins
  • Cartridges
  • S
  • Swords
  • Sparrows

So the items are ordered and group by the first letter. Missing letters are omitted. Does anyone have any ideas?

like image 226
Tudor Avatar asked Nov 11 '10 05:11

Tudor


1 Answers

Even easier. You can group by first leter just in 'regroup':

{% regroup items|dictsort:"name" by name.0 as item_letter %}
<ul>
{% for letter in item_letter %}
    <h4>{{ letter.grouper|title }}</h4>
    {% for i in letter.list|dictsort:"name" %}
        <li>{{ i.name }}</li>
    {% endfor %}
{% empty %}
    <span>There is no items yet...</span>
{% endfor %}
</ul>

name.0 in this case the same as item.name[0] in Python.

Tested in Django 1.10

like image 117
AndyMrk Avatar answered Sep 18 '22 18:09

AndyMrk