使用Whoosh自定义视图

时间:2012-02-19 20:05:49

标签: django django-haystack whoosh

我正在使用Haystack和Whoosh来构建网站的搜索引擎部分。 Whoosh在我的情况下工作得非常好但我需要从我的视图中显示额外的信息取决于搜索的内容。

在我的Django视图中,我使用类似这样的东西,其中dummy是要显示的信息:

    dummy = "dummy"
    return render_to_response('images/ib_large_image.html', {'dummy': dummy},
                            context_instance=RequestContext(request))

所以,基本上我想个性化搜索视图以将我的变量显示到搜索模板中。

以下是一些配置:

设置

    HAYSTACK_CONNECTIONS = {
    'default': {
    'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
    'PATH': os.path.join(os.path.dirname(__file__), 'whoosh_index'),
    'DEFAULT_OPERATOR': 'AND',
    'SITECONF': 'search_sites',
    'SEARCH_RESULTS_PER_PAGE': 20
        },
    }

search_sites.py

    import haystack
    haystack.autodiscover()

搜索>索引>图像板> image_text.txt

    {{ object.name }}
    {{ object.description }}

imageboard> search_indexes.py

    import datetime
    from haystack import indexes
    from imageboard.models import Image

    class ImageIndex(indexes.SearchIndex, indexes.Indexable):
        text = indexes.CharField(document=True, use_template=True)

        def get_model(self):
            return Image

        def index_queryset(self):
            """Used when the entire index for model is updated."""
            return self.get_model().objects.filter(uploaded_date__lte=datetime.datetime.now())

imageboard> urls.py

    urlpatterns = patterns('imageboard.views',
     (r'^search/', include('haystack.urls')),
    )

我像这样配置了我的视图,但它不起作用:

imageboard> views.py

    from haystack.views import SearchView
    def search(request):
       return SearchView(template='search.html')(request)

任何想法??

1 个答案:

答案 0 :(得分:0)

我建议你看看haystack“StoredFields”。它们存储搜索结果视图在搜索索引中需要访问的任何信息。额外的好处是搜索结果视图永远不需要命中数据库以呈现其内容。此外,您可以将每个搜索结果的输出预渲染到存储的字段

class ImageIndex(indexes.SearchIndex, indexes.Indexable):
    rendered = CharField(use_template=True, indexed=False)

然后,在名为search / indexes / myapp / image_rendered.txt:

的模板中
<h2>{{ object.title }}</h2>

<p>{{ object.content }}</p>

最后,在search / search.html中:

...

{% for result in page.object_list %}
    <div class="search_result">
        {{ result.rendered|safe }}
    </div>
{% endfor %}
相关问题