[Answered ]-Django ORM for loop to get queryset

1👍

Presuming that you want to list all others with their first 5 books (sorted alphabetically) and their total count of books on one page with a single fetch, you will need to use aggregations/annotations.

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

In your template:

{% 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 %}

This is just a SAMPLE and UNTESTED. It is just to get you started. Please consult the documentation. It makes use of the postgres specific ArrayAgg.

Leave a comment