I created a view for search function but it is not working. It is not filtering products
I created a search function for my Website In views.py:
def search_view(request):
query=request.GET.get("q")
if query:
products=Product.objects.filter(title__icontains=query,description__icontains=query).order_by("-date")
else:
products = Product.objects.none()
context={
"products":products,
"query":query
}
return render(request, 'core/search.html',context)
I created a template for search products in my website and in search.html
<form action="{% url 'core:search' %}" method="GET" class="search-form">
<input type="text" name="q" placeholder="Enter your product name..." class="search-input">
<button type="submit" class="search-button">Search</button>
</form>
But the search function is not working. I mean it is not finding product from my database
Please tell me what is wrong here?
The querying you are here writing checks if the text is present both in the title and the description. If you want to match items that have at least one of the two, you can use:
from django.db.models import Q
def search_view(request):
query = request.GET.get('q')
if query:
products = Product.objects.filter(
Q(title__icontains=query) | Q(description__icontains=query)
).order_by('-date')
else:
products = Product.objects.none()
context = {'products': products, 'query': query}
return render(request, 'core/search.html', context)
That being said, substring matches are not a good way to search: a small typo, a different ordering of words, a synonym, etc. will all fail.
Usually when searching it is better to use search technology like such as Solr, Elasticsearch, Whoosh [GitHub], Xapian, etc.
On PostgreSQL you can also use a __search lookup [Django-doc] and other search vector technology, although that will still not be very effective.