[Answered ]-Book count per genre for each author in django

2👍

This should work:

>>> stats = Book.objects.values('author__name','genre__name').annotate(Count('id')).order_by('author')
>>> for x in stats:
...     print x['author__name'], x['genre__name'], x['id__count']
... 
A1 G1 3
A1 G2 1
A2 G1 1
A2 G2 1
>>> new_book = Book(title='new_book', author=Author.objects.get(pk=2), genre=Genre.objects.get(pk=1))
>>> new_book.save()
>>> stats = Book.objects.values('author__name','genre__name').annotate(Count('id')).order_by('author')
>>> for x in stats:
...     print x['author__name'], x['genre__name'], x['id__count']
... 
A1 G1 3
A1 G2 1
A2 G1 2
A2 G2 1
>>> 

Then use regroup:

pass stats to template:

{% regroup stats by author__name as author_stats_list %}

<ul>
{% for author in author_stats_list %}
    <li>{{ author.grouper }}
    <ul>
        {% for item in author.list %}
        <li>{{ item.genre__name }} {{ item.id__count }}</li>
        {% endfor %}
    </ul>
    </li>
{% endfor %}
</ul>   
👤dting

Leave a comment