Skip to content

Instantly share code, notes, and snippets.

@rg3915
Created August 10, 2016 21:00
Show Gist options
  • Save rg3915/5bc76bd4c7cb28d7947e128024568755 to your computer and use it in GitHub Desktop.
Save rg3915/5bc76bd4c7cb28d7947e128024568755 to your computer and use it in GitHub Desktop.
Group_by first item of M2M in Django
# views.py
def books_list(self):
    books_name = {}
    total = 0
    for item in Author.objects.all().order_by('books__name'):
        first_book = item.books.first()
        if first_book:
            total += 1
            books_name[first_book] = books_name.get(first_book, 0) + 1
    return {'books_name': books_name, 'total_books': total}
# template.html
{% for book, quant in books_list.books_name.items %}
    <tbody>
        <tr>
            <td>{{ book }}</td>
            <td>{{ quant }}</td>
        </tr>
    </tbody>
{% endfor %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment