我在數據庫中有很多書籍。搜索數據庫不會返回任何內容(空的queryset)。如何在django中實現搜索功能?
在菜單中:
<form name="myform" method="POST" action="{% url 'search' %}">
{% csrf_token %}
<input type="text" name="search" placeholder="Search" />
</form>
views.py,
def search(request):
if request.method == 'POST':
book_name = request.POST.getlist('search')
try:
status = Add_prod.objects.filter(bookname__icontains=book_name)
#Add_prod class contains a column called 'bookname'
except Add_prod.DoesNotExist:
status = None
return render(request,"search.html",{"books":status})
else:
return render(request,"search.html",{})
我的模板文件,
{% if books %}
<a href="{% url 'buy_book' pk=books.pk %}">
<!--Upon successful search book image with hyperlink appears -->
<img src="{{books.image.url}}" alt="No Image"></a>
<p>{{books.bookname}}</p>
<p>Rs.{{books.price}}</p>
{% endif %}
適合某些用例,但您也應該查看基於文檔的搜索,以便根據您的需求發展。 https://docs.djangoproject.com/zh/dev/topics/db/search/#document-based-search – keni