在Django项目中,实现搜索框查询的功能(附代码)

 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>

# 将查询到的内容,显示为分页导航效果,具体代码看上篇文章【可以直接复制过来使用】:

http://t.csdnimg.cn/2oWcb


urls.py

path('book/search/', views.search_book, name='search_book')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值