django 中过滤图书列表的每位作者的图书数量
简短的问题。 我有两个模型:
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(...)
如何在模板中显示下一个内容:
Authors in selected books:
Author1: book_count
Author2: book_count
...
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
...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
让我们逐步构建查询。
首先,获取在
book_list
中拥有书籍的作者。诀窍是要意识到
book_list
中每本书的作者都会出现一次。然后我们可以使用 annotate 来统计作者出现的次数。在模板中,您可以执行以下操作:
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:
直接从模板使用它:
意味着
author.bookauthor_sets.all().count() #with python
您也可以这样做:
在模板中:
我希望这些信息应该有所帮助。
Use it directly from template:
means
author.bookauthor_sets.all().count() #with python
You can also do like this:
In the template:
I hope this information should help.