[英]Search with django Haystack
我在多个不同的时间跟随了多个不同的示例,但是似乎我一直都缺少一些东西。 ->简而言之,将whoosh或elasticsearch与干草堆一起使用,搜索结果将一无所获。
模型
class Note(models.Model):
user = models.ForeignKey(User)
title = models.CharField(max_length=200)
body = models.TextField()
pub_date = models.DateTimeField()
def __unicode__(self):
return self.title
形成
class NotesSearchForm(SearchForm):
def no_query_found(self):
return self.searchqueryset.all()
def search(self):
# First, store the SearchQuerySet received from other processing. (the main work is run internally by Haystack here).
sqs = super(NotesSearchForm, self).search()
# if something goes wrong
if not self.is_valid():
return self.no_query_found()
# you can then adjust the search results and ask for instance to order the results by title
sqs = sqs.order_by(title)
return sqs
观看次数
def search(request):
# we retrieve the query to display it in the template
form = NotesSearchForm(request.GET)
# we call the search method from the NotesSearchForm. Haystack do the work!
results = form.search()
return render(request, 'search.html', {'search_query' : search_query,
'notes' : results,
})
模板
<!-- EXTENDS BASE
================================================== -->
{% extends 'base.html' %}
<!-- NAVBAR
================================================== -->
{% block nav %}
{% include 'nav1.html' %}
{% endblock %}
<!-- Marketing messaging and featurettes
================================================== -->
<!-- Wrap the rest of the page in another container to center all the content. -->
{% block marketing %}
<div class="container marketing">
<!-- START THE FEATURETTES -->
<hr class="featurette-divider">
<div class="row featurette">
<div class="col-md-7">
<h2>Search</h2>
<form type="get" action="/search/">
<input type="text" name="q">
<button type="submit">Search</button>
</form>
<p>Your query "{{ search_query }} has returned {{ notes.count }} result{{ notes|pluralize }}"</p>
{% for note in notes %}
<h1>{{ note.title }}</h1>
<p>
{{ note.body }}
</p>
{% endfor %}
</div>
</div>
<hr class="featurette-divider">
<!-- /END THE FEATURETTES -->
</div><!-- /.container -->
{% endblock %}
我知道这有点长,但是我似乎无法弄清楚出了什么问题。 搜索页面正在运行,但是搜索文本时未找到结果。
我想以文本形式输入“ search_text”,并使其返回“ search_text”出现在数据库文档中的所有实例,并带有一定数量的令牌,如此前后。
| 标题| 用户| {之前的令牌数量}'search_text'{之后的令牌数量}
之所以不起作用,是因为我的机器上没有运行Elasticsearch。 因此,通过在机器上安装并运行elasticsearch服务器,我可以获得搜索结果。 可以在这里找到说明: http : //chriskief.com/2014/05/14/django-haystack-and-elasticsearch-part-1/
需要额外的pyelasticsearch和elasticsearch来运行搜索。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.