Django的草垛 - 查看结果,而无需搜索查询?(Django Haystack - Show r

2019-07-29 20:04发布

我想显示匹配即使搜索查询没有插入选定方面,所有结果。 类似一些商店的应用程序是如何工作的如亚马逊

e.g. Show all products which are "blue" and between $10-$100.

如果未指定搜索查询草垛不返回任何值。

任何想法如何,我可以避开它?

谢谢!

Answer 1:

如果有人还在寻找,有一个在草垛代码提出了一个简单的解决方案:

https://github.com/toastdriven/django-haystack/blob/master/haystack/forms.py#L34

class SearchForm(forms.Form):
    def no_query_found(self):
    """
    Determines the behavior when no query was found.

    By default, no results are returned (``EmptySearchQuerySet``).

    Should you want to show all results, override this method in your
    own ``SearchForm`` subclass and do ``return self.searchqueryset.all()``.
    """
    return EmptySearchQuerySet()


Answer 2:

为什么没有结果?

我想像你正在使用类似一个草垛搜索模板入门文档 。 如果没有查询该视图不显示任何内容:

{% if query %}
    {# Display the results #}
{% else %}
    {# Show some example queries to run, maybe query syntax, something else? #}
{% endif %}

第二个问题是,默认的搜索表单的search()方法实际上并不搜索任何东西,除非有一个查询。

获取结果

为了解决这个问题,我使用的是自定义的搜索表单。 这里有一个简短的示例:

class CustomSearchForm(SearchForm):
    ...
    def search(self):
        # First, store the SearchQuerySet received from other processing.
        sqs = super(CustomSearchForm, self).search()

        if not self.is_valid():
          return sqs

        filts = []

        # Check to see if a start_date was chosen.
        if self.cleaned_data['start_date']:
            filts.append(SQ(created_date__gte=self.cleaned_data['start_date']))

        # Check to see if an end_date was chosen.
        if self.cleaned_data['end_date']:
            filts.append(SQ(created_date__lte=self.cleaned_data['end_date']))

        # Etc., for any other things you add

        # If we started without a query, we'd have no search
        # results (which is fine, normally). However, if we
        # had no query but we DID have other parameters, then
        # we'd like to filter starting from everything rather
        # than nothing (i.e., q='' and tags='bear' should 
        # return everything with a tag 'bear'.)
        if len(filts) > 0 and not self.cleaned_data['q']:
            sqs = SearchQuerySet().order_by('-created_date')

        # Apply the filters
        for filt in filts:
            sqs = sqs.filter(filt)

        return sqs

另外,不要忘记改变看法:

{% if query or page.object_list %}
    {# Display the results #}
{% else %}
    {# Show some example queries to run, maybe query syntax, something else? #}
{% endif %}

实际上,视图代码是一个小的hackish。 它不区分查询较少的搜索,没有从一个不带参数的搜索结果。

干杯!



Answer 3:

看看SearchQuerySet 。

如果颜色和价格在你的SearchIndex定义这应该是可能的:

sqs = SearchQuerySet().filter(color="blue", price__range=(10,100))

您可以通过添加限制查询到某些型号models(Model)的SearchQuerySet。 所以,如果你想限制你的查询到模型物品使用:

sqs = SearchQuerySet().filter(color="blue", price__range=(10,100)).models(Item)


Answer 4:

下面的表格显示,如果没有查询字符串的所有结果存在。 现在,您可以添加自定义过滤器。

from your_app.forms import NonEmptySearchForm
url(r'^your_url$', 
SearchView(template='search.html',searchqueryset=sqs,form_class=NonEmptySearchForm), name='haystack_search'),

forms.py

#Overridding because the default sqs is always none if no query string is present
class NonEmptySearchForm(SearchForm):
    def search(self):
        if not self.is_valid():
            return self.no_query_found()
        sqs = self.searchqueryset.auto_query(self.cleaned_data['q'])
        if self.load_all:
            sqs = sqs.load_all()
        return sqs


Answer 5:

粗短的乔·皮特的回答是美丽的地方,但他提到,模板if query or page.object_list检查是有点黑。 解决这将是创建自己的一种更好的方式SearchForm它仍然会找到的东西,如果q是空的-不会转贴这一点-自定义SearchView喜欢的东西:

class MySearchView(SearchView):
    def get_query(self):
        query = []

        if self.form.is_valid():
            for field in self.form:
                if field.name in self.form.cleaned_data and self.form.cleaned_data[field.name]:
                    query.append(field.name+'='+str(self.form.cleaned_data[field.name]))

        return ' AND '.join(query)

在大多数情况下,你甚至不会使用该query值,所以你也可以同样做一个快速检查,如果任何字段的设置并返回True或类似的东西..或者你当然可以修改任何输出你想要的方式(我甚至100%肯定,我的解决方案将用于所有字段类型的工作,但你的想法)。



文章来源: Django Haystack - Show results without needing a search query?