圖書查詢

我們可以在顯示某本圖書的頁面,順便帶出這本圖書的借閱記錄,方便我們了解有哪些讀者在哪些時候借閱了這本書。

修改 library/book/views.py 用來處理檢視圖書的視圖類別 BookView,為其新增 get_context_data() 方法:

from django.contrib.auth.mixins import LoginRequiredMixin from .models import * from log.models import Log
class BookView(LoginRequiredMixin, DetailView): # 檢視圖書 model = Book def get_context_data(self, **kwargs): ctx = super().get_context_data(**kwargs) ctx['log_list'] = Log.objects.filter( book=self.object, ).order_by('-id').select_related('reader') return ctx

在 views 中取得所需資料後,接下來就可以修改頁面範本 library/templates/book/book_detail.html 插入第 28 - 58 行將借閱紀錄補上:

<div class="col-sm-8"> <div class="card"> <div class="card-header">{{ book.title }}</div> <table class="table"> <tr> <th>作者</th><td>{{ book.author }}</td> </tr> <tr> <th>出版社</th><td>{{ book.publisher }}</td> </tr> </table> </div> <div class="card"> <div class="card-header"> 借閱紀錄 </div> <ul class="list-group"> {% for log in log_list %} <li class="list-group-item d-flex justify-content-between"> <div> <span class="badge"> {{ log.checkout|date:"Y/m/d H:i" }} <i class="fas fa-arrow-alt-circle-right"></i> </span> {% if log.returned %} <span class="badge"> {{ log.returned|date:"Y/m/d H:i" }} </span> {% else %} <span class="badge badge-warning">借閱中</span> {% endif %} </div> <div> <a href="{% url 'reader_view' log.reader.id %}"> {{ log.reader.realname }} </a> </div> </li> {% empty %} <li class="list-group-item"></li> {% endfor %} </ul> </div> </div>