Adam
Adam

Reputation: 3128

Getting limited random items from related object in templates?

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

Answers (1)

Burhan Khalid
Burhan Khalid

Reputation: 174662

You have two options:

  1. 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]
    
  2. 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

Related Questions