我在Wagtail模板上有一个有效的搜索表单,该表单根据标签来查找页面,但是由于没有运算符(AND
或OR
),一次只能搜索一个标签。
有人可以建议我如何修改此代码以允许进行多个标签搜索吗?
models.py
tag_posts = PostsPage.objects.live().public().order_by('-first_published_at')
if request.GET.get('tag', None):
tags = request.GET.get('tag')
tag_posts = tag_posts.filter(tags__slug__in=[tags])
# Paginate all posts by 2 per page
paginator = Paginator(tag_posts, 2)
# Try to get the ?page=x value
page = request.GET.get("page")
try:
posts = paginator.page(page)
except PageNotAnInteger:
posts = paginator.page(1)
except EmptyPage:
posts = paginator.page(paginator.num_pages)
context["posts"] = tag_posts
return context
search_page.html
<form role="search" method="get" class="form-search" action="posts" method="get">
<div class="input-group">
<input type="text" class="form-control search-query" name="tag" placeholder="What are you after?" title="Search for:" />
<span class="input-group-btn">
<button type="submit" class="btn btn-default" name="" id="searchsubmit" value="">
<span class="btn btn-default">GO</span>
</button>
</span>
</div>
</form>
答案 0 :(得分:1)
您需要允许用户输入多个用逗号(或您选择的其他分隔符)分隔的标签。下面的代码允许将逗号,分号和竖线用作分隔符。它不使用空格作为分隔符,因为taggit的标签可以超过一个单词。
我会改变:
tag_posts = PostsPage.objects.live().public().order_by('-first_published_at')
if request.GET.get('tag', None):
tags = request.GET.get('tag')
tag_posts = tag_posts.filter(tags__slug__in=[tags])
收件人:
tag_string = request.GET.get('tag', None)
if tag_string:
tags = re.split('[,;|]', tag_string.lower())
tag_ids = Tag.objects.annotate(name_lower=Lower('name')).filter(name_lower__in=tags).values_list('id', flat=True)
tag_posts = PostsPage.objects.live().public().filter(tags__in=tag_ids).order_by('-first_published_at')
请注意,上面的代码是按标签名称而不是根据值来区分大小写的。
也可以:
import re
from django.db.models.function import Lower