Python Force django autocomplete=返回的灯光';最佳';先比赛
我有一个长长的项目列表,我正在使用Python Force django autocomplete=返回的灯光';最佳';先比赛,python,django,django-autocomplete-light,Python,Django,Django Autocomplete Light,我有一个长长的项目列表,我正在使用django autocomplete light字段搜索,其中autocomplete定义如下: class OccupationAutocomplete(autocomplete_light.AutocompleteModelBase): model = models.Occupation search_fields=['title',] 有些职位名称的字母顺序在列表中很靠前,例如: “老师” 在其他“不太理想的标题”之后,例如: “农业教
django autocomplete light
字段搜索,其中autocomplete定义如下:
class OccupationAutocomplete(autocomplete_light.AutocompleteModelBase):
model = models.Occupation
search_fields=['title',]
有些职位名称的字母顺序在列表中很靠前,例如:
“老师”
在其他“不太理想的标题”之后,例如:
“农业教师”、“建筑教师”、“建筑教师”等
我想要的是“最佳”匹配,或者是最接近的匹配,或者只是以搜索文本开头的匹配,因此如果有人搜索“teach”,他们会得到“teacher”,因为它以相同的字母开头,然后是其他不太准确的匹配
我已尝试使用首选顺序设置搜索\u字段
search_fields=['^title','title',]
但对这些术语的分析表明,这些术语在返回之前都被分解到一个查询中
如何以更合适的方式对该列表进行排序?最后,我必须实现一个新类,该类只接受按“首选权重”排序的词典列表,然后基于此返回结果
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)