django for循环只显示最后一次迭代

pinkon5k  于 2022-12-24  发布在  Go
关注(0)|答案(1)|浏览(140)

我正在构建一个图书推荐Django应用程序。我已经完成了机器学习模型的集成,但问题是它从我使用的csv文件中获取数据,而不是从我的数据库中。显示推荐图书的标题没有问题,但我想让用户查看该图书的详细信息页面。我需要从我的Book模型中获取推荐书籍的ID。
我对Django比较陌生,所以如果我的代码很乱,请原谅。
这是我的views.py的摘录:

def s_detail(request, book_id): #student paper detail
    cosine_sim = joblib.load('cosine_sim-v5.pkl') #load the ml model 
    data = pd.read_csv('try.csv', sep=',', encoding='utf-8')
    try:
        book = Book.objects.get(pk=book_id)
        fav = True 
        if book.favorites.filter(id=request.user.id).exists():
            fav=False
    
        def recommendations(book_id,n, cosine_sim = cosine_sim):
            recommended_books = []
            idx = book_id
            score_series = pd.Series(cosine_sim[idx]).sort_values(ascending = False)
            top_n_indexes = list(score_series.iloc[1:n+1].index)
            for i in top_n_indexes:
                recommended_books.append(list(data.index)[i]) # data.index for book_id column
            return recommended_books

        recommend = recommendations(book_id, 3) 
        for i in recommend: 
            new = Book.objects.filter(id=i) #to get the Book id from the model 
            print(new) #just to check if it's working

    except Book.DoesNotExist: 
        raise Http404("Title does not exist")    
    return render (request, 'books/s_detail.html', {'book':book, 'fav':fav, 'recommend':recommend, 'new':new})

在我模板中:

{% for book in new %}
    <div class="card">     
      <img src="/books/media/{{book.book_image}}" alt="bookimage"><br>
        <div class="browse-content">
            <b>Title:</b> <a href="{% url 's_detail' book.id %}"> {{book.book_title}} </a><br>
            <div class="eye">
                <i class="fa-solid fa-eye"></i> Views
            </div>
        </div>
    </div>
{% endfor %}

基于终端中的打印输出,迭代工作良好

[22/Dec/2022 10:27:42] "GET /books/s_browse HTTP/1.1" 200 27157
<QuerySet [<Book: Radioprotective Potential of Leaf Extract of Sapinit (Rubus rosifolius) On the Sperm Count and Sperm Morphology of y-Irradiated Mice (Mus musculus)>]>
<QuerySet [<Book: Analysis of Cytotoxic Activities of Select Plant Extracts against A549 - Lung Adenocarcinoma Cell Line>]>
<QuerySet [<Book: Inventory of Epiphytes on the Walls of Intramuros, Manila>]>

但仅显示模板中的最后一个小版本
我觉得我需要在某个地方存储这些值,但我不知道如何存储。

pieyvz9o

pieyvz9o1#

您正在for循环中使用大小为1的新QuerySet覆盖new变量。请尝试替换以下内容:

recommend = recommendations(book_id, 3) 
for i in recommend: 
    new = Book.objects.filter(id=i) #to get the Book id from the model 
    print(new) #just to check if it's working

用这个

recommend = recommendations(book_id, 3) 
new = Book.objects.filter(id__in=recommend)
print(new)

这将获取recommend列表中存在id值的所有Book示例。

相关问题