view.py
from django.db.models import Q
# Q 对象是从 django.db.models 导入的,用于创建复杂的查询条件
def search_book(request):
query = request.GET.get('query', '')
# 从GET请求中获取查询参数'query',如果该参数不存在,则默认为空字符串
objects = Book.objects.all()
# 初始查询集,Book模型为models.py中的对象
if query:
objects = objects.filter(
# 如果 query 不为空,使用 filter() 方法和 Q 对象来对查询集进行过滤
# filter过滤查询集并去除重复项
Q(book_name__icontains=query) |
Q(book_isbn__icontains=query) |
Q(book_author__icontains=query) |
Q(book_status__icontains=query)
# 这里使用了 icontains 查找选项,表示不区分大小写的包含查询
)
# 调用分页函数,这里per_page可以根据需求设置每页显示的数量
page_obj = paginate_queryset(objects, request, per_page=5)
# 渲染模板并传递分页对象和其他上下文
return render(request, 'user/user_首页.html', {'page_obj': page_obj, 'query': query})
models.py
class Book(models.Model):
# 图书信息表 book
book_id = models.AutoField(primary_key=True)
book_name = models.CharField(max_length=32)
book_isbn = models.CharField(verbose_name='图书的isbn',max_length=32)
book_author = models.CharField(verbose_name='图书的作者',max_length=32)
# 图书状态(0:未借阅,1:已借阅)
book_status_choices = (
(0, "未借阅"),
(1, "已借阅"),
)
book_status = models.SmallIntegerField(
verbose_name="图书状态",
choices=book_status_choices
)
user_首页.html
<form action="/book/search/" method="get">
<div>
<h1 align="left">查询图书</h1>
<div style="display: inline;">
<input type="text" name="query" value="{{ query }}" placeholder="请输入搜索内容" style="width: 65%; height: 35px"/>
<button type="submit" class="button" style="width: 60px; height: 25px;">查询
</button>
<button type="reset" class="button" style="width: 60px; height: 25px; margin-left: 1%">重置</button>
</div>
</div>
# 显示查询到的内容
{% if page_obj %}
<table border="1">
<tr>
<th width="250">图书ID</th>
<th width="250">图书名</th>
<th width="250">图书ISBN码</th>
<th width="250">图书作者</th>
<th width="250">图书状态</th>
</tr>
{% for book in page_obj %}
<tr>
<td>{{ book.book_id }}</td>
<td>{{ book.book_name }}</td>
<td>{{ book.book_isbn }}</td>
<td>{{ book.book_author }}</td>
<td>{{ book.book_status }}</td>
{% endfor %}
</tr>
{% else %}
<p>没有找到书籍</p>
{% endif %}
</table>
</form>
# 将查询到的内容,显示为分页导航效果,具体代码看上篇文章【可以直接复制过来使用】:
urls.py
path('book/search/', views.search_book, name='search_book')