Это должно работать:
>>> 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
>>>
Затем используйте regroup
:
передать статистику в шаблон:
{% 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>