添加视图函数
在view.py文件中添加视图函数,拿到请求,返回响应,给出数据,渲染页面
from django.shortchs import render
def search(request):
# 在表单中取carno,没取出给空值
carno = request.POST.get('carno','')
if carno:
#去掉拿到车牌中间的空字符
carno = carno.replace(' ', '')
# 通过Record这个模型的模型管理器的filter方法,通过car对象的carno属性去筛选出 # 和表单拿到的车牌号相同的记录,返回一个查询集对象
queryset = Record.objects.filter(car__carno=carno)
# 将查询集对象添加到字典中
context = {'records': queryset}
return render(request, 'index.html', context)
视图函数完成之后在urls.py文件添加视图函数的路径。
urlpatterns = [
……
path('search/',search),
]
修改模板页面index.html
<form id="form" action="/search/" method="post">
{% csrf_token %}
<input type="text" name="carno" placeholder="请输入车牌号或车主姓名"/>
<input type="submit" value="查询"/>
</form>
<hr /><br />
{% if records %}
<table>
<tr>
<th>车牌</th>
<th>车主</th>
<th>时间</th>
<th>地点</th>
<th>违章原因</th>
<th>处罚方式</th>
<th>是否受理</th>
<th>操作</th>
</tr>
{% for record in records %}
<tr>
<td>{{ record.car.car_no }}</td>
<td>{{ record.car.owner }}</td>
<td>{{ record.offend_time }}</td>
<td>{{ record.offend_place }}</td>
<td>{{ record.offend_reason }}</td>
<td>{{ record.punish }}</td>
<td>{{ record.dealed | yesno:'已受理,未受理' }}</td>
</tr>
{% endfor %}
</table>
{% else %}
<h3>没有查询到违章记录</h3>
{% endif %}
在重新运行项目,搜索框中输入要查询的车牌号信息。
![](https://img.haomeiwen.com/i20012812/150d8559e218f51e.png)
结果
![](https://img.haomeiwen.com/i20012812/e8d87988ab3052c9.png)
模糊查询+多条件查询
在字段后面加上
# 模糊查询
__exact #表示精确查询
__contains # 包含,相当于在字符串的头尾加%的模糊查询
__startswith # 表示以什么开头的模糊查询
__endswith # 表示以什么结尾的模糊查询
# 注意:如果在参数前面加i,表示忽略大小写的模糊查询。使用__contains和__endswith会导致程序性能很差。
queryset = Record.objects.filter(car__carno__istarswith=carno)
# 查询在Recor模型的模型管理器(objects)里面查询car对象的carno属性(忽略大小写、以什么开头)的记录,返回一个查询集。
Django中有个Q对象,,使用时需要导入,用于多条件查询,我们可以使用符号&或者|将多个Q()对象组合起来传递给filter(),exclude(),get()等函数 。
from django.db.models import Q
# | 表示‘或者’的意思
# & 表示’并且‘的意思
# ~ 表示‘非’的意思
#例如:
Q(car__carno__startswith='川A') | Q(car__owner__contains='王')
相当于SQL语句:
# select * from tb1 where carno like '川A%' or owner like '%王%';这样的查询语句。
# 车牌或者车主姓名模糊查询查询
queryset = Record.objects.filter(
Q(car__carno__istarswith=carno) |
Q(car__owner__contains=carno)
)
分页操作
可以对查询集进行切片操作来达到分页的效果。
def search(request):
context = {'searched': False}
if request.method == 'POST':
carno = request.POST.get('carno','')
# 将拿到的车牌做去掉空格,转大写处理
carno = carno.replace(' ', '').upper()
context['carno'] = carno
page = int(request.POST.get('page', '1'))
size = int(request.POST.get('size', '5'))
if carno:
context['searched'] = True
context['current_page'] = page
total = Record.objects.filter(
Q(car__carno__istarswith=carno) |
Q(car__owner__contains=carno)
).count()
# 总页数
context['total_page'] = math.ceil(total / size)
# 页面显示的记录的条偶数
queryset = Record.objects.filter(
Q(car__carno__istarswith=carno) |
Q(car__owner__contains=carno)
)[(page - 1) * size:page * size]
context['records'] = queryset
return render(request, 'index.html', context)
在视图函数中修改好之后,就可以去前端页面添加相应的模板语法。用Vue实现上一页,下一页的功能。
网友评论