Short question.
I have two models:
class Author(models.Model):
name = models.CharField(max_length=250)
class Book(models.Model):
title = models.CharField(max_length=250)
author = models.ManyToManyField(Author)
One view:
def filter_books(request):
book_list = Book.objects.filter(...)
How can I display in template next content:
Authors in selected books:
Author1: book_count
Author2: book_count
...
Let’s build the query step by step.
First, get the authors who have a book in
book_list.The trick is to realise that an author will appear once for each book in
book_list. We can then use annotate to count the number of times the author appears.In the template, you can then do: