我是django的新手,我正在开发一个项目,我需要创建一个搜索功能,用户可以在模型中搜索数据,我已经尝试过这种方式编码,但即使我搜索的是项目在模型中,它不会显示任何结果。
我真的需要帮助
view.py
def search(request):
query = request.GET.get('q')
results = Myhouses.objects.filter(Q(name_of_accomodation__icontains=query) | Q(type_of_room__icontains=query) | Q(location__icontains=query))
return render(request, 'account/index.html')
模板
<form method='GET' action='{% url "search" %}'>
<input type='text' name='q' placeholder="Enter Search Keyword" value='{{ request.GET.q }}' id='intry'>
<input type='submit' value='Search' class='button_1' id='sub1'>
</form>
答案 0 :(得分:3)
例如:
视图
def search(request):
query = request.GET.get('q')
results = Myhouses.objects.filter(Q(name_of_accomodation__icontains=query) | Q(type_of_room__icontains=query) | Q(location__icontains=query))
return render(request, 'account/index.html', {'results': results})
模板
<ul>
{% for element in results %}
<li>{{ element }}</li>
{% endfor %}
</ul>