【问题标题】:Django haystack querying databaseDjango haystack 查询数据库
【发布时间】:2014-05-05 22:47:10
【问题描述】:

我在引用视图上的特定字段时遇到了这个奇怪的问题,django 会进行 SQL 查询,尽管它是一个干草堆索引。

search_indexes.py

class StoreIndex(indexes.ModelSearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)        
    city = indexes.CharField(model_attr='city__name', faceted=True)
    region = indexes.CharField(model_attr='region__name', faceted=True)
    country = indexes.CharField(model_attr='country__name')
    created_at = indexes.DateTimeField(model_attr='created_at')
    tags = indexes.MultiValueField(model_attr='tags__names', faceted=True)

    def get_model(self):
        return Store

    def index_queryset(self, using=None):
    """Used when the entire index for model is updated."""
        return self.get_model().objects.filter(created_at__lte=datetime.datetime.utcnow())

urls.py

queryset = SearchQuerySet().facet('tags').facet('region').facet('city')

urlpatterns = patterns('haystack.views',
                   url(r'^search', FacetedSearchView(form_class=FacetedSearchForm, searchqueryset=queryset),
                       name='haystack_search'),
                   )

结果.html

<!-- Begin results. -->
        <div id="search-results">
            <ul>
            {% for result in page.object_list %}
                {% include 'search/_result_object.html' %}
                {% empty %}
                <p>No results found.</p>
            {% endfor %}               
            </ul>
        </div>
        <!-- End results. -->

_result_object.html

{% with object=result.object %}
<li class="search-result">
<section>
    <h3>{{ object.name }}</h3>
    <p>{{ object.addressLine1 }}, {{ object.addressLine2 }}, {{ object.addressLine3 }}   </p>
    <strong> {{ object.city }}, {{ object.region }} </strong>
    <strong class="pull-right"><a href="{% url 'store_detail' pk=object.id %}">Details</a></strong>
</section>
</li>
{% endwith %}

访问{{ object.city }}, {{ object.region }}时查询数据库

我已经验证,城市和地区都作为专有名称存储在弹性搜索中。

提前致谢。

【问题讨论】:

    标签: django django-haystack


    【解决方案1】:

    如果您使用任何 result.object.* 字段,它将执行数据库查找并访问您的 SQL 数据库。 尝试例如。直接result.city,应该使用索引中的数据,避免SQL DB命中。

    【讨论】:

    • 谢谢。刚刚更改为 {% with object=result %} 和 详细信息.
    • 如果您需要从数据库中获取对象但又不想每次都进行查询,您可以执行例如p_ids = [a.pk for a in results] 然后做例如Photo.objects.filter(id__in=p_ids)。这仅在您使用仅从一个模型返回结果的 Haystack 查询时才有效,例如r = SearchQuerySet().models(Photo).filter(text="Something here")
    猜你喜欢
    • 2011-05-22
    • 1970-01-01
    • 2015-05-08
    • 2018-03-03
    • 1970-01-01
    • 1970-01-01
    • 2019-03-30
    • 2016-07-10
    相关资源
    最近更新 更多