搜索 Django 逻辑

时间:2021-05-10 17:45:23

标签: 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!})

1 个答案:

答案 0 :(得分:0)

对于您的代码,如果您想在上下文中添加错误,请使用此逻辑。

  1. 过滤您的查询集 qs。
  2. 如果 qs 不为空 context = {'qs':qs}
  3. 如果 qs 为空 context = {'error': '您输入的关键字未找到!'}

所以代码看起来像这样:

if qs:
  context = {
    'qs':qs,
  }
else:
  context = {
    'error': 'The keyword you entered not found!'
  }
return render(request, 'posts/search.html',context)
相关问题