我正在构建一个图书推荐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>]>
但仅显示模板中的最后一个小版本
我觉得我需要在某个地方存储这些值,但我不知道如何存储。
1条答案
按热度按时间pieyvz9o1#
您正在
for
循环中使用大小为1的新QuerySet
覆盖new
变量。请尝试替换以下内容:用这个
这将获取
recommend
列表中存在id
值的所有Book
示例。