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