我正在尝试在 3 个字段名称、类别和标签中对我的对象使用搜索,所以现在类似项目三次
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代码
<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>
有可能类别和标签都匹配,因此互为“乘数”。您可以使用 .distinct()
[Django-doc] 检索唯一项目:
if search:
wallpapers = Wallpaper.objects.filter(
Q(name__icontains=search) | Q(category__category_name__icontains=search) | Q(tags__tag__icontains=search)
)<strong>.distinct()</strong>
views.py
if search:
wallpapers = Wallpaper.objects.filter(Q(name__icontains=search) | Q(category__category_name__icontains=search) | Q(tags__tag__icontains=search))
Html代码
<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>
有可能类别和标签都匹配,因此互为“乘数”。您可以使用 .distinct()
[Django-doc] 检索唯一项目:
if search:
wallpapers = Wallpaper.objects.filter(
Q(name__icontains=search) | Q(category__category_name__icontains=search) | Q(tags__tag__icontains=search)
)<strong>.distinct()</strong>