如何使用静态数据预填充AutoModelSelect2Field? (django-select2库)

时间:2013-03-10 14:31:12

标签: javascript ajax django json jquery-select2

我有一个如下字段:

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

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

1 个答案:

答案 0 :(得分:3)

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

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)