One simple question. I have 3 models:
class Author(models.Model):
name = models.CharField(max_length=250)
class Genre(models.Model):
name = models.CharField(max_length=250)
class Book(models.Model):
title = models.CharField(max_length=250)
author = models.ForeignKey(Author)
genre = models.开发者_JAVA百科ForeignKey(Genre)
How can I do template with next content:
Author1:
Genre1 - book count
Genre2 - book count
...
Author2:
Genre1 - book count
Genre2 - book count
...
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>
精彩评论