python-3.x - 搜索 Django 逻辑
问题描述
我在我的网络应用程序上编写了以下代码来搜索表单。现在,如果找不到搜索的对象,我想显示错误。我最后添加了 else 语句,但它显示错误。
def search(request):
qs = Post.objects.all()
location_query= request.GET.get('location')
details_query= request.GET.get('details')
user_query= request.GET.get('user')
days_query= request.GET.get('days')
people_query= request.GET.get('people')
date_query= request.GET.get('date')
gender_query= request.GET.get('gender')
if location_query !='' and location_query is not None:
qs=qs.filter(location__icontains=location_query)
elif details_query !='' and details_query is not None:
qs=qs.filter(detail__icontains=details_query)
elif user_query !='' and user_query is not None:
qs=qs.filter(author__icontains=user_query)
elif days_query !='' and days_query is not None:
qs=qs.filter(no_days__icontains=days_query)
elif people_query !='' and people_query is not None:
qs=qs.filter(no_people__icontains=people_query)
elif date_query !='' and date_query is not None:
qs=qs.filter(tour_date__icontains=date_query)
elif gender_query !='' and gender_query is not None:
qs=qs.filter(Gender_prefer__icontains=gender_query)
context = {
'qs':qs,
}
return render(request, 'posts/search.html',context)
我想在最后添加这个:
return render(request, 'posts/search.html', {'error':'The keyword you entered not found!})
解决方案
对于您的代码,如果您想在上下文中添加错误,请使用此逻辑。
- 过滤您的查询集 qs。
- 如果 qs 不为空 context = {'qs':qs}
- 如果 qs 为空 context = {'error': '您输入的关键字未找到!'}
所以代码将如下所示:
if qs:
context = {
'qs':qs,
}
else:
context = {
'error': 'The keyword you entered not found!'
}
return render(request, 'posts/search.html',context)
推荐阅读
- java-8 - 更新 ColdFusion 9 以使用 TLS 1.2
- javascript - 构建后在 index.html 中获取公共 URL
- java - 没有 Microsoft Word,documents4j 转换为 pdf 不起作用?
- json - SharePoint 联系人卡片列表视图格式不显示内容
- google-apps-script - 如何将图表从一个 Google 表格导入另一个 + 自动更新
- python - 如何使用 Redirect 函数重定向到 Python 中的另一个 URL
- python - Python 模拟 postgres 数据库
- c# - 进行 Jira API 调用时,没有附加标头的 GET 请求的“指定值具有无效的控制字符。参数名称:值”
- arrays - 我无法获得 result_array codeigniter 的总和数组(在 result_array 之后获得 num_rows)
- javascript - 通过数组映射并返回结果