django中每位作者的每种类型的书数

时间:2011-05-07 13:24:38

标签: django django-templates

一个简单的问题。我有3个型号:

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.ForeignKey(Genre)

如何使用下一个内容制作模板:

Author1:
    Genre1 - book count
    Genre2 - book count
    ...
Author2:
    Genre1 - book count
    Genre2 - book count
    ...

1 个答案:

答案 0 :(得分:2)

这应该有效:

>>> 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>