筛选草堆结果

2024-04-28 03:51:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图建立一个食谱全文搜索。我已将“成分”指定为“文档”字段。一切都很好,但我也想对搜索结果施加更多的限制。你知道吗

例如,我想对字段成分执行全文搜索,但希望只搜索与指定类别匹配的模型。你知道吗

我查看了文档,没有找到任何需要设置的查询参数,也没有找到任何必须对索引进行的更改。你知道吗

我在后台使用elasticsearch进行索引,如果有必要的话。你知道吗

class ArticleIndex(indexes.SearchIndex,indexes.Indexable):
    text = indexes.CharField(document=True,model_attr='ingredients')
    title = indexes.CharField(model_attr='title')
    category = indexes.CharField(model_attr='category')
    image_link = indexes.CharField(model_attr='image_link')
    publication_date = indexes.DateTimeField(model_attr='publication_date')

    def get_model(self):
        return Article

Tags: 文档imagedatemodeltitlelink类别全文
1条回答
网友
1楼 · 发布于 2024-04-28 03:51:06

如果你想缩小搜索结果的范围,你只需要使用一个自定义表单从用户那里获得额外的过滤信息,并在视图中使用这个输入来缩小SearchQuerySet。你知道吗

可能是这样的:

from django import forms
from haystack.forms import SearchForm
from haystack.generic_views import SearchView


class MySearchForm(SearchForm):
    category = forms.CharField(required=False)

    def search():
        sqs = super(MySearchForm, self).search()

        category = self.cleaned_data.get('category')

        if category:
            sqs = sqs.filter(category__exact=category)

        return sqs


class MySearchView(SearchView):
    form_class = MySearchForm

这只是一个很小的例子,我没有测试代码,但应该是这样的。您还可以在自定义表单中使用SelectMultipleSelect,让用户只选择表单预定义的类别。你知道吗

相关问题 更多 >