![](/img/trans.png)
[英]Only the last result of a for-loop iteration is being saved in a dictionary
[英]django for-loop only displaying the last iteration
我正在構建圖書推薦 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>]>
但只顯示模板中的最后一次迭代
我覺得我需要將值存儲在某個地方,但我不知道如何存儲。
您正在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
實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.