typeahead的远程自动完成功能仅适用于唯一查询

时间:2015-09-07 17:33:56

标签: autocomplete django-haystack typeahead.js typeahead bloodhound

我在两个字段中设置带有猎犬的预先输入有问题 - 符号和名称。您可以在我的DGI portfolio manager和自动填充远程来源here上尝试实时版本 Typeahead有时会起作用,有时却不起作用 如果我输入符号,如“jnj”,“mcd”,“aapl”就可以了。
但是,当我从名称键入字符串时,例如“corporation”和“inc”,其中包含大约3000个具有此名称的对象,它不起作用。我怀疑是因为它正在加载,因为json文件快速提供(在localhost下不到250毫秒) 首先,我认为符号正常工作,名称被忽略。但我确实为某些名字做了适当的预选:例如“苹果”和“家庭街” 我相信它只有在有1或2个结果时才有效。但我不明白,json文件总是提供最多5个结果 这是我的代码:
views.py for autocomplete url:

from haystack.query import SearchQuerySet
import json
def autocomplete(request):
    if request.GET.get('q', '') == '':
        array = []
    else:
        sqs = SearchQuerySet().models(Stock)
        sqs_symbol = sqs.filter(symbol_auto=request.GET.get('q', ''))
        sqs_name = sqs.filter(name_auto=request.GET.get('q', ''))
        sqs_result = sqs_symbol | sqs_name
        array = []
        print sqs_result.count()
        for result in sqs_result[:5]:
            data = {"symbol": str(result.symbol),
                     "name": str(result.name),
                     "tokens": str(result.name).split()
                    }
            array.insert(0, data)
        print array
    return HttpResponse(json.dumps(array), content_type='application/json')

我添加了print,所以我知道它什么时候不起作用。 search_indexes.py文件:

from haystack import indexes
from stocks.models import Stock

class StockIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    symbol = indexes.CharField(model_attr='symbol')
    name = indexes.CharField(model_attr='name')

    # We add this for autocomplete.
    symbol_auto = indexes.EdgeNgramField(model_attr='symbol')
    name_auto = indexes.EdgeNgramField(model_attr='name')

    def get_model(self):
        return Stock

    def index_queryset(self, using=None):
        """Used when the entire index for model is updated."""
        return self.get_model().objects.all()

在我的模板html文件中:

<script type="text/javascript">
    $(function(){
        var stocks = new Bloodhound({
            datumTokenizer: function (datum) {
                return Bloodhound.tokenizers.whitespace(datum.tokens);
            },
            queryTokenizer: Bloodhound.tokenizers.whitespace,
            limit: 5,
            remote: {
                url: "/search/autocomplete/",
                replace: function(url, query) {
                    return url + "?q=" + query;
                },
                filter: function(stocks) {
                    return $.map(stocks, function(data) {
                        return {
                            tokens: data.tokens,
                            symbol: data.symbol,
                            name: data.name
                        }
                    });
                }
            }
        });
        stocks.initialize();
        $('.typeahead').typeahead(null, {
                name: 'stocks',
                displayKey: 'name',
                minLength: 1, // send AJAX request only after user type in at least X characters
                source: stocks.ttAdapter(),
                templates: {
                    suggestion: function(data){
                      return '<p>' + data.name + ' (<strong>' + data.symbol + '</strong>)</p>';
                    }
                }
        }).on('typeahead:selected', function (obj, stock) {
            window.location.href = "/stocks/detail/" + stock.symbol;
        });
    });
</script>

编辑:一些例子
jnj autocomplete
Json response

[{"tokens": ["Johnson", "&", "Johnson"], "symbol": "JNJ", "name": "Johnson & Johnson"}]

不适用于“sto”:
not working typeahead.js
json response

[{"tokens": ["QKL", "Stores,", "Inc."], "symbol": "QKLS", "name": "QKL Stores, Inc."}, {"tokens": ["SPDR", "DJ", "STOXX", "50"], "symbol": "FEU", "name": "SPDR DJ STOXX 50 "}, {"tokens": ["Statoil", "ASA"], "symbol": "STO", "name": "Statoil ASA"}, {"tokens": ["STORE", "Capital", "Corporation"], "symbol": "STOR", "name": "STORE Capital Corporation"}, {"tokens": ["StoneMor", "Partners", "L.P."], "symbol": "STON", "name": "StoneMor Partners L.P."}]

1 个答案:

答案 0 :(得分:1)

typeahead.js's bug。它应该在版本0.11.2中修复。