Django ORM for循环获取queryset



我正在尝试使用for循环来获取作者列表,其中包含所写书籍的数量和作者的书名。这是我的型号.py

class Author(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name

class Book(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
def __str__(self):
return self.title

我试着这样循环:

for a in Author.all():
books = a.book_set.order_by('author')
print(books)

我得到的作者是他们在数据库。此外,

for book in book_set.iterator():
...     print(book.title)

我拿到了所有书籍的清单。

我使用author_list = Author.objects.order_by("book").count(),它给出了作者的编号。我如何在数据库中循环并获得书籍数量的作者和书名的作者。

假设您想通过一次提取将所有其他人的前5本书(按字母顺序排列(和他们在一页上的图书总数列出,则需要使用聚合/注释。

Author.objects.annotate(
book_count=Count('book'),
book_list=ArrayAgg('book__title', ordering='book__title')
).order_by('name').all()

在您的模板中:

{% for author in author_list %}
{author.name} ({author.book_count}):
<ul>
{% for book_title in author.book_list %}
<li>{book_title}</li>
{% endfor %}
</ul>
{% endfor %}

这只是一个样本和未测试。这只是为了让你开始。请查阅文档。它使用了postgres特定的ArrayAgg。

最新更新