django中筛选出的图书清单的每个作者的书数 [英] book count per author for filtered book list in django

查看:387
本文介绍了django中筛选出的图书清单的每个作者的书数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简短的问题。
我有两个模型:

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)

一个视图:

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


推荐答案

让我们逐步构建查询。

首先,在 book_list 中找到拥有一本书的作者。

First, get the authors who have a book in book_list.

authors = Author.objects.filter(book__in=book_list)

诀窍是要认识到,对于 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 %}

这篇关于django中筛选出的图书清单的每个作者的书数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆