book count per author for filtered book list in django

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-04 16:41:25

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!