红联Linux门户
Linux帮助

Django+haystack+solr:配置让django站点用solr来搜索

发布时间:2015-01-08 11:50:12来源:linux网站作者:leequery

1、首先当然得创建新的项目:django-admin startproject testsolr

manage.py startapp note


2、修改settings文件,添加haystack相关配置及db配置

haystack相关:HAYSTACK_SITECONF = 'note.search_sites'

HAYSTACK_SEARCH_ENGINE = 'solr'

HAYSTACK_SOLR_URL = 'http://127.0.0.1:8080/solr/'

DATABASES 配置本文省略,请根据自己的情况进行相应配置;

INSTACLLED_APPS 里面需添加haystack和note

至此,django部分需要配置的就这些。

说明:note app中需要新建编辑search_indexes.py search_sites.py,编辑完成后执行manage.py build_solr_schema,

将输出的信息保存至schema.xml并覆盖至solr配置文件所在文件夹下的schema.xml,然后执行manage.py rebuild_index.


3、urls配置,url(r'^search/', include('haystack.urls'))

这个默认会调用haystack的模板,默认在templates下缺少search/search.html,故需要创建:代码如下

{% block content %}
<h2>Search</h2>
<form method="get" action=".">
<table>
{{ form.as_table }}
<tr>
<td>&nbsp;</td>
<td>
<input type="submit" value="Search">
</td>
</tr>
</table>
{% if query %}
<h3>Results</h3>
{% for result in page.object_list %}
<p>
<a href="{{ result.object.get_absolute_url }}">{{ result.object.title }}</a>
</p>
{% empty %}
<p>No results found.</p>
{% endfor %}
{% if page.has_previous or page.has_next %}
<div>
{% if page.has_previous %}<a href="?q={{ query }}&amp;page={{ page.previous_page_number }}">{% endif %}&laquo; Previous{% if page.has_previous %}</a>{% endif %}
|
{% if page.has_next %}<a href="?q={{ query }}&amp;page={{ page.next_page_number }}">{% endif %}Next &raquo;{% if page.has_next %}</a>{% endif %}
</div>
{% endif %}
{% else %}
{# Show some example queries to run, maybe query syntax, something else? #}
{% endif %}
</form>
{% endblock %}