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
.
authors = Author.objects.filter(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.
# remember to import Count!
from django.db.models import Count
authors = Author.objects.filter(book__in=book_list
).annotate(num_books=Count('id')
In the template, you can then do:
Authors in selected books:
{% for author in authors %}
{{ author.name }}: {{ author.num_books }}<br />
{% endfor %}
#first way
class Author(models.Model):
name = models.CharField(max_length=250)
class Book(models.Model):
title = models.CharField(max_length=250)
author = models.ManyToManyField(Author, related_name='bookauthor_sets')
Use it directly from template:
{{ author.bookauthor_sets.all.count }}
means
author.bookauthor_sets.all().count() #with python
You can also do like this:
#second one
class Author(models.Model):
name = models.CharField(max_length=250)
def get_books_count(self):
return Book.objects.filter(author=self).count()
In the template:
{{ author.get_books_count }}
I hope this information should help.