Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I am trying to use search on my object in 3 fields name, category, and tags, so now similar item three time

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="/" class="d-flex">
  <input class="form-control me-2" name="search" id="search" type="search" placeholder="Search"
                    aria-label="Search">
  <button class="btn btn-outline-success" type="submit">Search</button>
</form>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading