Rad*_*Hex 10 python django search solr django-haystack
即使未插入搜索查询,我也希望显示与所选方面匹配的所有结果.与某些商店应用程序的工作方式类似,例如Amazon
e.g. Show all products which are "blue" and between $10-$100.
如果未指定搜索查询,Haystack不会返回任何值.
我有什么想法可以解决它吗?
谢谢!
Ere*_*ezO 12
如果有人还在寻找,那么在haystack代码中建议使用一个简单的解决方案:
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()
Run Code Online (Sandbox Code Playgroud)
小智 6
我想你正在使用类似于大海捞针入门文档中的搜索模板.如果没有查询,则此视图不显示任何内容:
{% if query %}
{# Display the results #}
{% else %}
{# Show some example queries to run, maybe query syntax, something else? #}
{% endif %}
Run Code Online (Sandbox Code Playgroud)
第二个问题是默认搜索表单的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
Run Code Online (Sandbox Code Playgroud)
另外,不要忘记更改视图:
{% if query or page.object_list %}
{# Display the results #}
{% else %}
{# Show some example queries to run, maybe query syntax, something else? #}
{% endif %}
Run Code Online (Sandbox Code Playgroud)
实际上,视图代码有点hackish.它不区分无查询搜索,没有没有参数的搜索结果.
干杯!
如果您的 SearchIndex 中已经定义了颜色和价格,那么这应该是可能的:
sqs = SearchQuerySet().filter(color="blue", price__range=(10,100))
Run Code Online (Sandbox Code Playgroud)
models(Model)您可以通过添加到 SearchQuerySet将查询限制为某些模型。因此,如果您想将查询限制为模型 Item 使用:
sqs = SearchQuerySet().filter(color="blue", price__range=(10,100)).models(Item)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4782 次 |
| 最近记录: |