简短的问题。 我有两个模型:
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
...
答案 0 :(得分:3)
让我们逐步构建查询。
首先,让拥有book_list
书籍的作者。
authors = Author.objects.filter(book__in=book_list)
诀窍是要意识到作者将在book_list
中为每本书出现一次。然后我们可以使用注释来计算作者出现的次数。
# remember to import Count!
from django.db.models import Count
authors = Author.objects.filter(book__in=book_list
).annotate(num_books=Count('id')
在模板中,您可以执行以下操作:
Authors in selected books:
{% for author in authors %}
{{ author.name }}: {{ author.num_books }}<br />
{% endfor %}
答案 1 :(得分:0)
#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')
直接在模板中使用:
{{ author.bookauthor_sets.all.count }}
装置
author.bookauthor_sets.all()。count()#with python
你也可以这样做:
#second one
class Author(models.Model):
name = models.CharField(max_length=250)
def get_books_count(self):
return Book.objects.filter(author=self).count()
在模板中:
{{ author.get_books_count }}
我希望这些信息可以提供帮助。