【问题标题】:Custom view does not show results in Django Haystack with Elastic Search自定义视图在 Django Haystack 中不显示结果与 Elastic Search
【发布时间】:2018-01-15 07:30:05
【问题描述】:

我开始使用 Django Haystack 和 Elasticsearch。

好吧,直到我按照readthedocs 中的简单示例开始制作自定义视图。

search_indexes.py:

class ExperimentIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    owner = indexes.CharField(model_attr='owner')

    def get_model(self):
        return Experiment

    def index_queryset(self, using=None):
        return self.get_model().lastversion_objects.all()

urls.py:

url(r'^search/?$', NepSearchView.as_view(), name='search_view')

urls.py 之前(没有自定义视图):

url(r'^search/', include('haystack.urls'))

views.py

class NepSearchView(SearchView):

    def get_queryset(self):
        queryset = super(NepSearchView, self).get_queryset()
        if not self.request.user.is_authenticated and \
                self.request.user.groups.filter(name='trustees').exists():
            return queryset  # (with some filter)
        else:
            return queryset

search.html:

{# ... #}
{% for result in page.object_list %}
{% if result.model_name == 'experiment' %}
{% include 'search/experiments.html' %}
{% endif %}
{% if result.model_name == 'study' %}
{% include 'search/studies.html' %}
{% endif %}
{% if result.model_name == 'group' %}
{% include 'search/groups.html' %}
{% endif %}
{% if result.model_name == 'experimentalprotocol' %}
{% include 'search/experimental_protocol.html' %}
{% endif %}
{# ... #}

事实上,当使用默认 Haystack SearchView 时,我得到了正确的匹配,而在引入 NepSearchView 时,page.object_list 是空的,而我在模板中得到了 No results found.

我已经运行了manage.py rebuild_index,在网络上进行了广泛的搜索,但找不到任何可以解释我所缺少的东西。

【问题讨论】:

    标签: python django elasticsearch django-views django-haystack


    【解决方案1】:

    查询集的 page.object_list 变量名似乎不存在。 试试不带“page”前缀的object_list

    而不是

    {% for result in page.object_list %}
    

    使用

    {% for result in object_list %}
    

    或者,您可以通过附加类似这样的内容在视图中提供自定义变量名称

    context_object_name = 'haystack_objects'
    

    并在模板中使用它

    {% for result in haystack_objects %}
    

    【讨论】:

    • 晚了,但我想我会问:你是如何诊断这个问题的?我挣扎了几个小时,精确匹配文档中的教程,尽管仍然使用带有page.object_list 的默认模板。很想知道将来如何避免类似的头痛。
    猜你喜欢
    • 1970-01-01
    • 2014-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-29
    • 1970-01-01
    相关资源
    最近更新 更多