Home > Enterprise >  I am trying to use search on my object in 3 fields name, category, and tags, so now similar item thr
I am trying to use search on my object in 3 fields name, category, and tags, so now similar item thr

Time:01-04

views.py

 if search:
     wallpapers = Wallpaper.objects.filter(Q(name__icontains=search) | Q(category__category_name__icontains=search) | Q(tags__tag__icontains=search))

Html code

<form method="GET" action="/" >
  <input  name="search" id="search" type="search" placeholder="Search"
                    aria-label="Search">
  <button  type="submit">Search</button>
</form>

CodePudding user response:

It is possible that both the category and the tag match, and thus act as a "multiplier" for each other. You can work with .distinct() [Django-doc] to retrieve unique items:

if search:
    wallpapers = Wallpaper.objects.filter(
        Q(name__icontains=search) | Q(category__category_name__icontains=search) | Q(tags__tag__icontains=search)
    ).distinct()
  •  Tags:  
  • Related