Reputation: 3128
I have an Author model with many books assigned to each one. In my Books model I have: author = models.ForeignKey(Author)
In my page, I am listing all the authors I have and under each author I want to display 5 random books.
Is this feasible through the templates only or I must do that in my view? I mean limiting the results and getting them randomly.
I'm currently only passing the authors to template, like this: a = Author.objects.all()
Please advise.
Upvotes: 1
Views: 73
Reputation: 174662
You have two options:
Do it in your view:
This query is "return 5 random books for author a
"
random_books = Book.objects.filter(author=a).order_by('?')[:5]
Create a custom tag that takes an author and returns random 5 books:
Create a custom tag:
from myapp.models import Book
def randbooks(author):
return {'books': Book.objects.filter(author=author).order_by('?')[:5]}
register.inclusion_tag('book_listing.html')(randbooks)
Create a template to show the titles (book_listing.html
):
<ul>
{% for book in books %}
<li>{{ book }}</li>
{% endfor %}
</ul>
Use it in your template like this:
{% for author in a %}
{% randbooks author %}
{% endfor %}
Upvotes: 4