4

我有一个如下字段:

class ContactSelect(AutoModelSelect2Field):
    queryset = Contact.objects.all()
    search_fields = ['name__contains']
    to_field = 'name'
    widget = AutoHeavySelect2Widget

它工作正常,但只有在我输入 2 个字母后才开始加载,而我希望它在 html 中包含最相关的选择,并在用户仅输入 1 个字母时搜索它们。那么你会推荐什么方法呢?是否可以使用django-select2(显然是select2本身)来做到这一点,或者我会为此编写自己的 JS 函数?

4

1 回答 1

4

可能的解决方案是允许空搜索,因此即使搜索字段中没有任何内容,列表中也会有一些项目。

django-select2 视图总是在“get”方法中跳过空词,所以我们需要覆盖它:

class MySelect2ResponseView(AutoResponseView):
  def get(self, request, *args, **kwargs):
    term = request.GET.get('term')
    if term == "":
        return self.render_to_response(self._results_to_context(self.get_results(request, term, -1, None)))
    return super(MySelect2ResponseView, self).get(request, *args, **kwargs)

现在“”术语将进入您的领域的“get_results”方法:

class ContactSelectWidget(AutoHeavySelect2Widget):
  def __init__(self, *args, **kwargs):
    kwargs['select2_options'] = {
      # this will allow select2 to send empty search to server 
      'minimumInputLength': 0, 
      # it's needed, otherwise search field will be hided by select2 
      'minimumResultsForSearch': 0, 
    }
    super(ContactSelectWidget, self).__init__(*args, **kwargs)

class ContactSelect(AutoModelSelect2Field):
  widget = ContactSelectWidget 
  queryset = Contact.objects.all()
  search_fields = ['name__contains']
  to_field = 'name'

  def get_results(self, request, term, page, context):
    if term == "":
      # return anything you want here:  
      return ('nil', False, [(1, "my_item1", {}), (2, "my_item2", {})])
    else:
      return super(ContactSelect, self).get_results(request, term, page, context)
于 2013-06-09T10:42:36.193 回答