我正在创建一个博客,我希望在该博客中根据评分(1-5)进行搜索查询。在这里,我的搜索就像查询:“智能手机技术更新”,等级:“ 3”。结果应该是包含val排序方式为3的查询词(至少一个词)的帖子列表(至少一个单词)(在val(对于每个查询词,如果在标题val + = 1中找到,如果在内容val + = 0.4中找到))。
我的models.py文件具有以下内容:
class Post(models.Model):
title = models.CharField(max_length=50)
content = models.CharField(max_length=500)
rating = models.IntegerField(default=1)
enter code here
date = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
我的view.py文件具有以下内容:
def search(request):
contents = Post.objects.all()
if request.method == 'GET':
query = request.GET['query']
rating = request.GET['rating']
# search function
# contents = InSearch.search_fun(contents,query,rating)
vector = SearchVector('title', weight='A') + SearchVector('content', weight='B')
qry = SearchQuery(str(query))
contents = Post.objects.annotate(rank=SearchRank(vector, qry)).order_by('-rank')
#print("---->\n\t"+query+ str(contents))
context = {
'contents': contents
}
else:
context = {
'contents': Post.objects.all()
}
return render(request, 'feed/home.html', context)
我的urls.py是:
urlpatterns = [
#...
path('feed/search-result/', views.search, name='feed_search'),
]
我收到此错误
django.db.utils.OperationalError: no such function: plainto_tsquery
答案 0 :(得分:1)
您可以在视图中尝试这样进行搜索。
from django.db.models import Q
def search(request):
q = request.GET.get('q')
if q:
search_results = Post.objects.filter(Q(title__icontains=q)|Q(rating=q))
# if you want the exact then do Post.objects.filter(Q(title__iexact=q) & Q(rating=q))
return render(request, 'feed/home.html','search_results':search_results)
else:
messages.info(request,'no results found for {}',format(q))
如果您要按匹配数对搜索查询结果进行排序,则可以这样尝试:
search_results = Post.objects.filter(Q(title__icontains=q)|Q(rating=q)).annotate(title_counts=Count('title')).order_by('-title_counts')
然后在您的模板中的搜索表单中输入name='q'
。
<form action="{% url 'your search action' %}">
<input type="text" name="q">
<input type='submit' value='Search'>
</form>