Django search bar isn't giving correct results

Question:

views.py

from django.shortcuts import render
from ecommerceapp.models import Product
from django.db.models import Q

def searchResult(request):
    products=None
    query=None
    if 'q' in request.GET:
        query = request.GET.get('q')
        products=Product.objects.all().filter(Q(name__contains=query) | Q(desc__contains=query))
    return render(request,'search.html',{'query':query,'products':products})

In views.py I have imported a model named ‘Product’ of another application.

search.html

{% extends 'base.html' %}
{% load static %}

{% block metadescription %}
    Welcome to FASHION STORE-Your Beauty
{% endblock %}

{% block title %}
   Search-FASHION STORE
{% endblock %}

{% block content %}
<div>
    <p class="text-center my_search_text">You have searched for :<b>"{{query}}"</b></p>
</div>
<div class="container">
    <div class="row mx_auto">
        {% for product in products %}
            <div class="my_bottom_margin col-9 col-sm-12 col-md-6 col-lg-4" >
                <div class="card text-center" style="min-width:18rem;">
                    <a href="{{product.get_url1}}"><img class="card-img-top my_image" src="{{product.image.url}}" alt="{{product.name}}" style="height:400px; width:100%;"></a>
                    <div class="card_body">
                        <h4>{{product.name}}</h4>
                        <p>₹{{product.price}}</p>
                    </div>
                </div>
            </div>
            {% empty %}
            <div class="row mx_auto">
                <p class="text-center my_search_text">0 results found.</p>
            </div>
            {% endfor %}
    </div>
</div>
{% endblock %}

navbar.html

<nav class="navbar navbar-expand-lg bg-light">
  <div class="container-fluid">
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav me-auto mb-2 mb-lg-0">
        <li class="nav-item">
          <a class="nav-link" href="#">Home</a>
        </li>
        <li class="nav-item dropdown {% if 'ecommerceapp' in request.path %} active {% endif %} ">
          <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
            Shop
          </a>
          <ul class="dropdown-menu">
            <li><a class="dropdown-item" href="{% url 'ecommerceapp:allProductCategory' %}">All Products</a></li>
            {% for cat in links %}
                <li><a class="dropdown-item" href="{{cat.get_url}}">{{cat.name}}</a></li>
            {% endfor %}
          </ul>
        </li>
        <li class="nav-item">
          <a class="nav-link disabled" href=""><i class="fa fa-shopping-cart"></i></a>
        </li>
      </ul>
      <form class="d-flex" action="{% url 'search_app:searchResult' %}" method="get">
        {% csrf_token %}
        <input class="form-control me-2" type="search" placeholder="Search" name="q" aria-label="Search">
        <button class="btn btn-outline-success" type="submit"><i class="fa fa-search"></i></button>
      </form>
    </div>
  </div>
</nav>

When I’m searching using search bar, not getting the correct results. When giving the word completely, correct results are getting.

Example: When I type x in the search bar, it give me the results ‘shirt’ instead of giving ‘0 results found’.

Asked By: Jimna

||

Answers:

Example: When I type x in the search bar, it give me the results ‘shirt’ instead of giving ‘0 results found’.

The __contains is used to check whether the field contains given word or not, it is case-sensitive. And using | in Q objects means it is optional and works as OR condition, so maybe it is possible when you type x, the name field doesn’t contains x but the field desc contain x that’s why you are getting the shirt as instance or else you can simply put the query to Product.objects.filter(Q(name__contains=query)) and .all() only creates the copy of the Queryset so it doesn’t require here.

Answered By: Dishant singhal
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.