0

我有一长串我正在使用django-autocomplete-light字段搜索的项目,自动完成定义如下:

class OccupationAutocomplete(autocomplete_light.AutocompleteModelBase):
    model = models.Occupation
    search_fields=['title',]

一些职位在列表中按字母顺序排列很远,例如:

“老师”

它出现在其他“不太理想的标题”之后,例如:

“农业老师”、“建筑老师”、“建筑老师”等……

我想要的是“最佳”匹配,无论是最接近还是仅以搜索文本开头的匹配,所以如果有人搜索“teach”,他们会得到“teacher”,因为它以相同的字母开头,并且然后是其他不太准确的匹配。

我尝试search_fields使用首选顺序进行设置

    search_fields=['^title','title',]

但是对自动完成代码的分析表明,这些术语在返回之前都被整合到一个查询中。

我将如何以更合适的方式订购此列​​表?

4

1 回答 1

0

最后我不得不实现一个新类,它只接受一个按“首选权重”顺序排列的字典列表,然后根据它返回结果。

class OrderedAutocomplete(autocomplete_light.AutocompleteModelBase):
    ordered_search_fields = []

    def choices_for_request(self):
        """
        Return a queryset based on :py:attr:`choices` using options
        :py:attr:`split_words`, :py:attr:`search_fields` and
        :py:attr:`limit_choices`.
        """
        assert self.choices is not None, 'choices should be a queryset'
        q = self.request.GET.get('q', '')
        exclude = self.request.GET.getlist('exclude')

        base_split_words = self.split_words

        _choices = []
        for weight,opt in enumerate(self.ordered_search_fields):
            if len(_choices) >= self.limit_choices:
                break

            search_fields = opt['search_fields']
            self.split_words = opt['split_words'] or base_split_words

            conditions = self._choices_for_request_conditions(q,
                    search_fields)
            choices = self.order_choices(self.choices.filter(conditions).exclude(pk__in=exclude))
            if choices.count():
                _choices += list(choices)[0:self.limit_choices]

        return _choices[0:self.limit_choices]

然后可以使用以下方法实例化:

class OccupationAutocomplete(OrderedAutocomplete):
    model = models.Occupation

    ordered_search_fields = [
        {'search_fields': ['^title'], 'split_words':False},
        {'search_fields': ['title'], 'split_words':True},
        ]
autocomplete_light.register(OccupationAutocomplete)
于 2015-11-02T23:29:57.450 回答