[Django]-Book object is not iterable: Trying to display similar objects of an instance based on a field

2👍

You need to pass the result of the similar books to the template, so:

def search_similar_results(request, slug):
    book = get_object_or_404(Book, slug=slug)
    books = book.similar_book()
    return render(request, 'book/similar_results.html', {'books': books})

In the DetailView, you can pass the `similar books with:

class BookDetail(generic.DetailView):
    model = Book
    context_object_name = 'book'
    template_name = 'book/detail.html'

    def similar_books(self):
        return self.object.similar_book()

Then in the template we work with:

{% for item in view.similar_books %}
    <!-- … -->
{% endfor %}

Leave a comment