我正在尝试django-haystack飞快移动。 Django Haystack和Whoosh搜索有效,但页面中没有给出结果。我也查过这个类似的问题
Django-haystack-whoosh is giving no results
Django Haystack & Whoosh Search Working, But SearchQuerySet Return 0 Results
点冻结
python==3.6
django==2.0.7
Whoosh==2.7.4
-e git://github.com/django-haystack/django.haystack.git#egg=django-haystack
这是我的代码:
search_indexes.py
import datetime
from haystack import indexes
from search.models import Articles
class ArticlesIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document = True, use_template = true
pub_date = indexes.DateTimeField(model_attr = 'pub_date')
content_auto = indexes.EdgeNgramField(model_attr='title')
def get_model(self):
return Articles
def index_queryset(self, using=None)
return self.get_model().objects.filter(pub_date__lte=datetime.datetime.now())
views.py
from .models import Articles
from haystack.query import SearchQuerySet
def home(request):
article=SearchQuerySet().autocomplete(content_auto=request.POST.get('search_text', '')
return render(request, 'home.hmtl')
home.html
<form method='post'action=''>
{% csrf_token %}
<table>
{{form.as_table}}
<tr>
<td><input type='search'></td>
<td><input type='submit' value= 'Search'></td>
</tr>
</table>
{% if query %}
<h3>Results</h3>
{% for article in articles %}
<p><a href="{{article.object.get_absolute_url}}">{{article.object.title}}</a></p>
{% empty %}
<p>No results found </p>
{% endfor %}
{% endif %}
</form>
models.py
from django.db import models
class Articles(models.Model):
title = models.CharField(max_length = 255)
body = models.TextField()
pub_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
projectfile / templates / indexes / search / articles_text.txt
{{object.title}}
{{object.body}}
settings.py
INSTALLED_APPS = [
'haystack',
'whoosh',
]
WHOOSH_INDEX=[os.path.join(BASE_DIR, 'whoosh/'),]
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
'PATH': os.path.join(os.path.dirname(__file__), 'whoosh_index'),
},
}
我运行了python3 manage.py rebuild_index,它说在app文件夹中索引了3条文章和我的search_indexes.py文件。
答案 0 :(得分:0)
Mistake在您的视图中,在视图中您未呈现文章,因此视图应为:
def home(request):
articles = SearchQuerySet().autocomplete(content_auto=request.POST.get('search_text', '')
return render(request, 'home.html', {'articles':articles})
为什么要使用自动完成功能?