2011-05-07 70 views
1

一個簡單的問題。我有3種型號:每個作者在django中的每個作者的書數

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

回答

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

優秀的答案!謝謝! – maksymov 2011-05-07 21:56:19

相關問題