安装haystack $ pip install django-haystack
需要安装并配置好solr,详见:猛击这里,接下来开始配置Django,首先在项目目录中新建search_sites.py文件,内容是:
import haystack haystack.autodiscover()
INSTALLED_APPS = ( #other apps 'haystack', ) HAYSTACK_SITECONF = 'search_sites' #之前创建的文件名 HAYSTACK_SEARCH_ENGINE = 'solr' HAYSTACK_SOLR_URL = 'http://127.0.0.1:8080/solr/'#solr所在服务器 HAYSTACK_SOLR_TIMEOUT = 60 * 5 HAYSTACK_INCLUDE_SPELLING = True HAYSTACK_BATCH_SIZE = 100 HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.solr_backend.SolrEngine', 'URL': 'http://127.0.0.1:8080/solr' #solr所在服务器 }, }在 urls.py里引入haystack:
url(r'^search/', include('haystack.urls')),
{% block content %} <h2>Search</h2> <form method="get" action="."> <table> {{ form.as_table }} <tr> <td> </td> <td> <input type="submit" class="btn btn-success" value="Search"> </td> </tr> </table> {% if query %} <h3>Results</h3> {% for result in page.object_list %} <p> <a href="#">{{ result.object.name }}</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 }}&page={{ page.previous_page_number }}">{% endif %}« Previous{% if page.has_previous %}</a>{% endif %} | {% if page.has_next %}<a href="?q={{ query }}&page={{ page.next_page_number }}">{% endif %}Next »{% if page.has_next %}</a>{% endif %} </div> {% endif %} {% else %} {# Show some example queries to run, maybe query syntax, something else? #} {% endif %} </form> {% endblock %}
from haystack import indexes, site from apps.products.models import Product class TestIndex(indexes.SearchIndex): text = indexes.CharField(document=True, use_template=True) title = indexes.CharField(model_attr='name') def get_model(self): return Product def index_queryset(self): return self.get_model().objects.all() site.register(search_test, TestIndex)但现在还无法搜索,要生成一个与现有Model对应的schema,把它写入Solr:
python manage.py build_solr_schema > /etc/solr/conf/schema.xml
另可以能不需要模板来实现搜索,而是写一个接口提供给客户端,在上面的基础上做如下操作:
from haystack.query import SearchQuerySet sqs = SearchQuerySet().auto_query(query_string=q) #q 为查询条件然后根据具体需求来对查询结果集sqs操作。
另更新solr索引只需要:
python manage.py update_index