本文介绍了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
中的每本书,作者都会出现一次.然后我们可以使用annotate来统计作者出现的次数.
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 中过滤图书列表的每位作者的图书计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!